| 1 |
/** |
| 2 |
* Creates sidebar blocks. |
| 3 |
*/ |
| 4 |
import { useState } from '@wordpress/element'; |
| 5 |
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd'; |
| 6 |
import { Icon } from '@wordpress/components'; |
| 7 |
|
| 8 |
function DragAndDropComponent( { |
| 9 |
initialItems, |
| 10 |
updateDefaultAllowedQuickSidebarBlocks, |
| 11 |
saveOptionToDatabase, |
| 12 |
} ) { |
| 13 |
const [ items, setItems ] = useState( initialItems ); |
| 14 |
|
| 15 |
const onDragEnd = ( result ) => { |
| 16 |
if ( ! result.destination ) { |
| 17 |
return; |
| 18 |
} |
| 19 |
const reorderedItems = Array.from( items ); |
| 20 |
const [ removed ] = reorderedItems.splice( result.source.index, 1 ); |
| 21 |
reorderedItems.splice( result.destination.index, 0, removed ); |
| 22 |
const namesArray = reorderedItems.map( ( item ) => item.name ); |
| 23 |
saveOptionToDatabase( namesArray ); |
| 24 |
setItems( reorderedItems ); |
| 25 |
updateDefaultAllowedQuickSidebarBlocks( namesArray ); |
| 26 |
}; |
| 27 |
|
| 28 |
return ( |
| 29 |
<DragDropContext onDragEnd={ onDragEnd }> |
| 30 |
<Droppable droppableId="droppable"> |
| 31 |
{ ( provided ) => ( |
| 32 |
<div |
| 33 |
className="srfm-ee-quick-access__sidebar--blocks" |
| 34 |
{ ...provided.droppableProps } |
| 35 |
ref={ provided.innerRef } |
| 36 |
> |
| 37 |
{ items.map( ( item, index ) => ( |
| 38 |
<Draggable |
| 39 |
key={ item.id } |
| 40 |
draggableId={ item.id } |
| 41 |
index={ index } |
| 42 |
> |
| 43 |
{ ( |
| 44 |
provided // eslint-disable-line no-shadow |
| 45 |
) => ( |
| 46 |
<div |
| 47 |
className="srfm-ee-quick-access__sidebar--blocks--block" |
| 48 |
ref={ provided.innerRef } |
| 49 |
{ ...provided.draggableProps } |
| 50 |
{ ...provided.dragHandleProps } |
| 51 |
> |
| 52 |
<div |
| 53 |
className={ `srfm-ee-quick-access__sidebar-icon__${ |
| 54 |
item?.name?.split( '/' )[ 0 ] |
| 55 |
} srfm-ee-quick-access__sidebar-icon__${ |
| 56 |
item?.name?.split( '/' )[ 0 ] |
| 57 |
}--${ |
| 58 |
item?.name?.split( '/' )[ 1 ] |
| 59 |
} srfm-ee-quick-access__sidebar--blocks--block--icon` } |
| 60 |
> |
| 61 |
<Icon |
| 62 |
icon={ |
| 63 |
item.icon.src |
| 64 |
? item.icon.src |
| 65 |
: item.icon |
| 66 |
} |
| 67 |
/> |
| 68 |
</div> |
| 69 |
</div> |
| 70 |
) } |
| 71 |
</Draggable> |
| 72 |
) ) } |
| 73 |
{ provided.placeholder } |
| 74 |
</div> |
| 75 |
) } |
| 76 |
</Droppable> |
| 77 |
</DragDropContext> |
| 78 |
); |
| 79 |
} |
| 80 |
|
| 81 |
export default DragAndDropComponent; |
| 82 |
|