To enable dropping workout blocks anywhere within the graph (not just at the end) while maintaining the expected draggable and droppable behavior, you'll need to adjust how you handle drag-and-drop interactions in your components. This involves:
- Allowing Blocks to Be Inserted at Specific Positions: Modify the
addBlockToGraph function to accept an index where the new block should be inserted.
- Updating Drop Targets: Adjust the
Graph and GraphBlock components to handle dropping WORKOUT_BLOCKs at any position within the graph.
- Handling Different Drag Types: Ensure that both
WORKOUT_BLOCK (new blocks) and GRAPH_BLOCK (existing blocks) can be dragged and dropped appropriately.
Below are the detailed steps and code modifications to achieve this functionality.
1. Update App.js to Allow Inserting at Specific Indexes
Modify the addBlockToGraph function to include an optional index parameter, allowing insertion at a specific position within the graphBlocks array.
// App.js
import React, { useState, useCallback, useRef } from 'react';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import Header from './Header';
import WorkoutBlocks from './WorkoutBlocks';
import Graph from './Graph';
import ColumnsList from './ColumnsList';
function App() {
const [graphBlocks, setGraphBlocks] = useState([]);
const idRef = useRef(0); // Persistent ID counter
// Function to add a new block to the Graph at a specific index
const addBlockToGraph = useCallback((block, index = graphBlocks.length) => {
if (!block.type || !block.height) {
console.error('Invalid block:', block);
return;
}
const newBlock = { ...block, id: idRef.current++ };
setGraphBlocks((prevBlocks) => {
const updatedBlocks = [...prevBlocks];
updatedBlocks.splice(index, 0, newBlock);
return updatedBlocks;
});
}, [graphBlocks.length]);
// Function to move (rearrange) a block within the Graph
const moveGraphBlock = useCallback((dragIndex, hoverIndex) => {
setGraphBlocks((prevBlocks) => {
const updatedBlocks = [...prevBlocks];
const [removed] = updatedBlocks.splice(dragIndex, 1);
updatedBlocks.splice(hoverIndex, 0, removed);
return updatedBlocks;
});
}, []);
// Function to remove a block from the Graph
const removeBlockFromGraph = useCallback((id) => {
setGraphBlocks((prevBlocks) => prevBlocks.filter((block) => block.id !== id));
}, []);
return (
<DndProvider backend={HTML5Backend}>
<div className="justify-center min-h-screen bg-[#F8F8F8] w-full p-4">
<Header />
{/* Main content */}
<div className="flex justify-between mx-6 my-3 items-start">
{/* Workout blocks card */}
<WorkoutBlocks />
{/* Graph and Columns List */}
<div className="w-full ml-6">
<Graph
blocks={graphBlocks}
addBlockToGraph={addBlockToGraph}
moveBlock={moveGraphBlock}
removeBlock={removeBlockFromGraph}
/>
<ColumnsList blocks={graphBlocks} />
</div>
</div>
</div>
</DndProvider>
);
}
export default App;
Explanation:
- Add an
index Parameter: The addBlockToGraph function now accepts an index parameter, defaulting to the end of the array (graphBlocks.length).
- Insert at Specific Position: Using
splice, the new block is inserted at the specified index. This allows flexibility in where new blocks are added within the graphBlocks array.
2. Modify Graph.js to Pass addBlockToGraph to GraphBlock
Update the Graph component to pass the addBlockToGraph function to each GraphBlock. This allows each block to handle drops of new WORKOUT_BLOCKs at specific positions.
// Graph.js
import React from 'react';
import GraphBlock from './GraphBlock';
const Graph = ({ blocks, addBlockToGraph, moveBlock, removeBlock }) => {
return (
<div
className="graph-container relative w-full h-[300px] bg-[#EAEAEA] rounded-lg shadow-md p-4 mb-4"
>
{/* Bar Graph */}
<div className="absolute inset-0 flex items-end space-x-2 px-2">
{blocks.map((block, index) => (
<GraphBlock
key={block.id}
id={block.id}
index={index}
block={block}
moveBlock={moveBlock}
removeBlock={removeBlock}
addBlockToGraph={addBlockToGraph} // Pass the function
totalBlocks={blocks.length}
/>
))}
</div>
{/* X-Axis Labels */}
<div className="absolute bottom-0 w-full flex justify-between text-xs mt-1">
{blocks.map((_, index) => (
<span key={index}>{index + 1} km</span>
))}
</div>
{/* Y-Axis Labels */}
<div className="absolute left-0 top-0 h-full flex flex-col justify-between text-xs mr-1">
<span>100%</span>
<span>75%</span>
<span>50%</span>
<span>25%</span>
<span>0%</span>
</div>
</div>
);
};
export default Graph;
Explanation:
- Remove the Universal Drop Target: The original
useDrop from the Graph component was allowing blocks to be dropped only at the end. By removing it, we prevent automatic addition at the end.
- Pass
addBlockToGraph: The addBlockToGraph function is now passed down to each GraphBlock, enabling each block to handle insertions at specific positions.
3. Enhance GraphBlock.js to Handle Dropping Both GRAPH_BLOCK and WORKOUT_BLOCK
Update the GraphBlock component to handle two types of draggable items:
GRAPH_BLOCK: Existing blocks being rearranged within the graph.
WORKOUT_BLOCK: New blocks being added from the WorkoutBlocks component.
// GraphBlock.js
import React, { useRef } from 'react';
import { useDrag, useDrop } from 'react-dnd';
const GraphBlock = ({
id,
index,
block,
moveBlock,
removeBlock,
addBlockToGraph,
totalBlocks,
}) => {
const ref = useRef(null);
const [, drop] = useDrop({
accept: ['GRAPH_BLOCK', 'WORKOUT_BLOCK'],
hover(item, monitor) {
if (!ref.current) {
return;
}
const hoverBoundingRect = ref.current.getBoundingClientRect();
const hoverMiddleX = (hoverBoundingRect.right - hoverBoundingRect.left) / 2;
const clientOffset = monitor.getClientOffset();
const hoverClientX = clientOffset.x - hoverBoundingRect.left;
if (item.type === 'GRAPH_BLOCK') {
const dragIndex = item.index;
const hoverIndex = index;
// Don't replace items with themselves
if (dragIndex === hoverIndex) {
return;
}
// Only perform move when the mouse has crossed half of the item's width
if (dragIndex < hoverIndex && hoverClientX < hoverMiddleX) {
return;
}
if (dragIndex > hoverIndex && hoverClientX > hoverMiddleX) {
return;
}
// Perform the move
moveBlock(dragIndex, hoverIndex);
// Note: we're mutating the monitor item here!
// Generally it's better to avoid mutations,
// but it's good here for the sake of performance
item.index = hoverIndex;
}
if (item.type === 'WORKOUT_BLOCK') {
const hoverIndex = index;
// Add the new block before the current hover index
addBlockToGraph(item, hoverIndex);
// Optionally, you might want to set some state to indicate the block has been added
}
},
});
const [{ isDragging }, drag] = useDrag({
type: 'GRAPH_BLOCK',
item: { type: 'GRAPH_BLOCK', id, index },
collect: (monitor) => ({
isDragging: monitor.isDragging(),
}),
});
// Connect drag and drop
drag(drop(ref));
const handleRemove = () => {
removeBlock(id);
};
// Safety check
if (!block) {
console.error(`GraphBlock with id ${id} is undefined`);
return null;
}
return (
<div
ref={ref}
className={`relative bg-[#4339F280] rounded cursor-move flex flex-col items-center`}
style={{
width: `calc(${100 / totalBlocks}% - 8px)`, // Even width distribution
height: `${block.height}%`,
marginRight: index !== totalBlocks - 1 ? '8px' : '0',
opacity: isDragging ? 0.5 : 1,
transition: 'opacity 0.2s',
}}
>
{/* Remove Button */}
<button
onClick={handleRemove}
className="absolute top-0 right-0 bg-red-500 text-white rounded-full w-4 h-4 flex items-center justify-center text-xs"
>
×
</button>
{/* Display Block Type */}
<div className="text-xs text-white">{block.type}</div>
</div>
);
};
export default GraphBlock;
Explanation:
- Accept Multiple Types: The
useDrop hook now accepts both 'GRAPH_BLOCK' and 'WORKOUT_BLOCK'.
- Handle
GRAPH_BLOCK: If the dragged item is a GRAPH_BLOCK, it performs the usual rearrangement logic based on the hover position.
- Handle
WORKOUT_BLOCK: If the dragged item is a WORKOUT_BLOCK, it calls addBlockToGraph with the current hoverIndex, effectively inserting the new block before the hovered block.
- Drag Type: Ensure that
WORKOUT_BLOCKs are treated differently from GRAPH_BLOCKs to prevent conflicts.
4. Ensure WorkoutBlocks.js Uses the Correct Drag Type
Make sure that the draggable workout blocks are using the 'WORKOUT_BLOCK' type, which aligns with how we're handling drops in GraphBlock.
// WorkoutBlocks.js
import React from 'react';
import { useDrag } from 'react-dnd';
import { FiInfo } from 'react-icons/fi';
const WorkoutBlock = ({ children, type, height }) => {
const [{ isDragging }, drag] = useDrag({
type: 'WORKOUT_BLOCK', // Ensure the type matches what's accepted in GraphBlock
item: { type, height },
collect: (monitor) => ({
isDragging: monitor.isDragging(),
}),
});
return (
<div
ref={drag}
className={`relative bg-gray-200 rounded-lg overflow-hidden h-20 cursor-pointer ${
isDragging ? 'opacity-50' : 'opacity-100'
}`}
>
{children}
</div>
);
};
const WorkoutBlocks = () => {
return (
<div className="bg-white p-6 rounded-lg shadow-md max-w-sm w-full">
<div className="flex justify-between items-center mb-3">
<h2 className="text-lg font-semibold">Click or drag the blocks to build workout</h2>
<FiInfo className="text-gray-400 text-2xl" />
</div>
<hr className="border-gray-300 mb-4" />
<div className="grid grid-cols-2 gap-3">
<WorkoutBlock type="block50" height={50}>
<div className="absolute bottom-0 w-full h-1/2" style={{ background: '#4339F280' }}></div>
</WorkoutBlock>
<WorkoutBlock type="block75" height={75}>
<div className="absolute bottom-0 w-full h-3/4" style={{ background: '#4339F280' }}></div>
</WorkoutBlock>
<WorkoutBlock type="block30" height={30}>
<div className="absolute bottom-0 w-full h-1/3" style={{ background: '#4339F280' }}></div>
</WorkoutBlock>
{/* Single block with two columns */}
<WorkoutBlock type="block60_40" height={60}>
<div className="flex h-full gap-1 transform scale-y-[-1] ">
<div className="w-1/2 h-3/5" style={{ background: '#4339F280' }}></div>
<div className="w-1/2 h-2/5" style={{ background: '#4339F280' }}></div>
</div>
</WorkoutBlock>
{/* Single block with four columns */}
<WorkoutBlock type="block80_60_40_20" height={80}>
<div className="flex h-full gap-1 transform scale-y-[-1]">
<div className="w-1/4 h-1/5" style={{ background: '#4339F280' }}></div>
<div className="w-1/4 h-2/5" style={{ background: '#4339F280' }}></div>
<div className="w-1/4 h-3/5" style={{ background: '#4339F280' }}></div>
<div className="w-1/4 h-4/5" style={{ background: '#4339F280' }}></div>
</div>
</WorkoutBlock>
{/* Another single block with reversed four columns */}
<WorkoutBlock type="block20_40_60_80" height={20}>
<div className="flex h-full gap-1 transform scale-y-[-1] ">
<div className="w-1/4 h-4/5" style={{ background: '#4339F280' }}></div>
<div className="w-1/4 h-3/5" style={{ background: '#4339F280' }}></div>
<div className="w-1/4 h-2/5" style={{ background: '#4339F280' }}></div>
<div className="w-1/4 h-1/5" style={{ background: '#4339F280' }}></div>
</div>
</WorkoutBlock>
</div>
</div>
);
};
export default WorkoutBlocks;
Explanation:
- Ensure Correct Type: The
useDrag hook in WorkoutBlock is set to 'WORKOUT_BLOCK', which matches the accept types in GraphBlock. This ensures that when these blocks are dragged, they are recognized correctly by the drop targets.
5. (Optional) Handle Dropping on the Graph Container for Appending at the End
If you still want to allow dropping directly on the graph container to append blocks at the end, you can keep a universal drop target in Graph.js. However, ensure that this doesn't conflict with dropping between existing blocks.
Here's how you can optionally keep both behaviors:
// Graph.js (with universal drop target)
import React from 'react';
import GraphBlock from './GraphBlock';
import { useDrop } from 'react-dnd';
const Graph = ({ blocks, addBlockToGraph, moveBlock, removeBlock }) => {
const [{ isOver, canDrop }, drop] = useDrop({
accept: 'WORKOUT_BLOCK',
drop: (item, monitor) => {
// Append to the end
addBlockToGraph(item);
return { name: 'Graph' };
},
collect: (monitor) => ({
isOver: monitor.isOver(),
canDrop: monitor.canDrop(),
}),
});
const isActive = isOver && canDrop;
return (
<div
ref={drop} // Universal drop target for appending
className={`graph-container relative w-full h-[300px] bg-[#EAEAEA] rounded-lg shadow-md p-4 mb-4
${isActive ? 'bg-[#D3D3D3]' : ''}
`}
>
{/* Bar Graph */}
<div className="absolute inset-0 flex items-end space-x-2 px-2">
{blocks.map((block, index) => (
<GraphBlock
key={block.id}
id={block.id}
index={index}
block={block}
moveBlock={moveBlock}
removeBlock={removeBlock}
addBlockToGraph={addBlockToGraph}
totalBlocks={blocks.length}
/>
))}
</div>
{/* X-Axis Labels */}
<div className="absolute bottom-0 w-full flex justify-between text-xs mt-1">
{blocks.map((_, index) => (
<span key={index}>{index + 1} km</span>
))}
</div>
{/* Y-Axis Labels */}
<div className="absolute left-0 top-0 h-full flex flex-col justify-between text-xs mr-1">
<span>100%</span>
<span>75%</span>
<span>50%</span>
<span>25%</span>
<span>0%</span>
</div>
</div>
);
};
export default Graph;
Explanation:
- Universal Drop Target: The
useDrop hook on the Graph component now allows dropping WORKOUT_BLOCKs directly onto the graph area, which appends them to the end.
- Potential Conflict: Be cautious as this universal drop might conflict with the individual
GraphBlock drop targets. Ensure that the individual blocks handle their drop events first.
6. Final Thoughts and Testing
After implementing the above modifications:
- Test Dragging Existing Blocks: Ensure that you can drag existing
GRAPH_BLOCKs to reorder them within the graph.
- Test Adding New Blocks: Drag
WORKOUT_BLOCKs from the WorkoutBlocks component and drop them between any two existing GRAPH_BLOCKs or at the end.
- Ensure State Consistency: Verify that the
graphBlocks state in App.js accurately reflects the changes after each drag-and-drop action.
- Handle Edge Cases: Consider scenarios like dragging to the very start or end of the graph, and ensure blocks are inserted correctly.
By following these steps and making the outlined code modifications, you should achieve a flexible drag-and-drop interface where workout blocks can be inserted anywhere within the graph seamlessly.