/** * Drag-and-drop state machine for the header builder canvas. * * Manages a set of named containers (header zones, or the single mobile list) * plus a synthetic palette of not-yet-placed elements. Elements are unique * across the canvas, so an element id doubles as its sortable id. Cross-zone * moves are applied optimistically on drag-over (so siblings reflow live); * the settled result is committed to the working settings tree on drop. * * Generic over both the multi-zone header canvas and the single-list mobile * off-canvas builder — both feed `containers` (zones only) and receive the * same `onCommit( zones )` back. */ import { useCallback, useEffect, useRef, useState } from '@wordpress/element'; import { KeyboardSensor, PointerSensor, useSensor, useSensors, type DragEndEvent, type DragOverEvent, type DragStartEvent, } from '../../dnd'; import { arrayMove, sortableKeyboardCoordinates } from '../../dnd'; export const PALETTE = '__palette__'; export type Containers = Record< string, string[] >; interface UseCanvasDndArgs { /** Zone id → ordered element ids (excludes the palette). */ containers: Containers; /** Full element order; palette = these minus everything placed. */ allIds: string[]; /** Persist the zones (palette stripped) back to the working tree. */ onCommit: ( zones: Containers ) => void; } const buildItems = ( containers: Containers, allIds: string[] ): Containers => { const placed = new Set( Object.values( containers ).flat() ); const palette = allIds.filter( ( id ) => ! placed.has( id ) ); const clone: Containers = {}; Object.keys( containers ).forEach( ( key ) => { clone[ key ] = [ ...containers[ key ] ]; } ); clone[ PALETTE ] = palette; return clone; }; const stripPalette = ( items: Containers ): Containers => { const zones: Containers = {}; Object.keys( items ).forEach( ( key ) => { if ( key !== PALETTE ) { zones[ key ] = items[ key ]; } } ); return zones; }; export function useCanvasDnd( { containers, allIds, onCommit, }: UseCanvasDndArgs ) { const [ items, setItems ] = useState< Containers >( () => buildItems( containers, allIds ) ); const [ activeId, setActiveId ] = useState< string | null >( null ); const [ pendingCommit, setPendingCommit ] = useState( false ); const draggingRef = useRef( false ); // Refs so the re-sync effect can read the latest props without depending // on their (per-render fresh) object identity. const containersRef = useRef( containers ); containersRef.current = containers; const allIdsRef = useRef( allIds ); allIdsRef.current = allIds; // Re-seed local items whenever the committed settings change outside a // drag (saves, resets, inline edits, or our own commit round-trip). // Value-keyed so it fires on real changes, not on every parent render. const containersKey = JSON.stringify( containers ); const allIdsKey = JSON.stringify( allIds ); useEffect( () => { if ( ! draggingRef.current ) { setItems( buildItems( containersRef.current, allIdsRef.current ) ); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [ containersKey, allIdsKey ] ); // Commit the fully-settled items once the drag ends (state has flushed). useEffect( () => { if ( ! pendingCommit ) { return; } onCommit( stripPalette( items ) ); setPendingCommit( false ); }, [ pendingCommit, items, onCommit ] ); const sensors = useSensors( useSensor( PointerSensor, { activationConstraint: { distance: 4 } } ), useSensor( KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates, } ) ); const findContainer = useCallback( ( id: string ): string | undefined => { if ( id in items ) { return id; } return Object.keys( items ).find( ( key ) => items[ key ].includes( id ) ); }, [ items ] ); const onDragStart = useCallback( ( event: DragStartEvent ) => { draggingRef.current = true; setActiveId( String( event.active.id ) ); }, [] ); const onDragOver = useCallback( ( event: DragOverEvent ) => { const { active, over } = event; if ( ! over ) { return; } const activeIdStr = String( active.id ); const overIdStr = String( over.id ); const from = findContainer( activeIdStr ); const to = findContainer( overIdStr ); if ( ! from || ! to || from === to ) { return; } setItems( ( prev ) => { const fromList = [ ...prev[ from ] ]; const toList = [ ...prev[ to ] ]; const fromIndex = fromList.indexOf( activeIdStr ); if ( -1 === fromIndex ) { return prev; } fromList.splice( fromIndex, 1 ); const overIndex = toList.indexOf( overIdStr ); const insertAt = -1 === overIndex ? toList.length : overIndex; toList.splice( insertAt, 0, activeIdStr ); return { ...prev, [ from ]: fromList, [ to ]: toList }; } ); }, [ findContainer ] ); const onDragEnd = useCallback( ( event: DragEndEvent ) => { const { active, over } = event; draggingRef.current = false; setActiveId( null ); if ( over ) { const activeIdStr = String( active.id ); const overIdStr = String( over.id ); const container = findContainer( overIdStr ); setItems( ( prev ) => { if ( ! container ) { return prev; } const list = prev[ container ]; const oldIndex = list.indexOf( activeIdStr ); const newIndex = list.indexOf( overIdStr ); if ( -1 === oldIndex || -1 === newIndex || oldIndex === newIndex ) { return prev; } return { ...prev, [ container ]: arrayMove( list, oldIndex, newIndex ), }; } ); } setPendingCommit( true ); }, [ findContainer ] ); /** Remove a placed element (returns it to the palette) and persist. */ const removeItem = useCallback( ( id: string ) => { const from = findContainer( id ); if ( ! from || PALETTE === from ) { return; } const zones = stripPalette( items ); zones[ from ] = zones[ from ].filter( ( x ) => x !== id ); onCommit( zones ); }, [ findContainer, items, onCommit ] ); /** * Drop any optimistic mid-drag moves and show the committed layout again — * for a drag that has left the zones for a target this hook doesn't own * (the header's off-canvas drawer). */ const reset = useCallback( () => setItems( buildItems( containersRef.current, allIdsRef.current ) ), [] ); /** End a drag without committing anything. */ const cancel = useCallback( () => { draggingRef.current = false; setActiveId( null ); reset(); }, [ reset ] ); return { items, activeId, reset, cancel, sensors, onDragStart, onDragOver, onDragEnd, removeItem, }; }