To achieve the desired behavior where users can drag and drop workout blocks anywhere within the graph (not just at the end), you'll need to refine your drag-and-drop implementation using React DnD. The goal is to allow users to insert blocks between existing ones based on their drop position.
Here's a step-by-step guide to modify your current implementation:
-
Understand the Current Structure:
- App.js: Manages the overall state and provides functions to add, move, and remove blocks.
- Graph.js: Acts as a universal drop target that currently appends new blocks to the end.
- GraphBlock.js: Represents individual blocks within the graph, each acting as both a drag source and a drop target.
- WorkoutBlocks.js: Contains the list of draggable workout blocks.
-
Identify the Issue:
- Currently, when a user drags a
WORKOUT_BLOCK and drops it on the graph, it's always appended to the end because the Graph.js component handles the drop uniformly.
- The desired behavior is to insert the block at the specific position where it's dropped, similar to how items are rearranged within a list.
-
Solution Overview:
- Enable Each
GraphBlock to Act as a Drop Target: This allows the insertion of new blocks before the hovered block.
- Maintain a Single Source of Truth for Adding Blocks: Ensure that the drop is handled either by the
Graph.js (for appending) or by individual GraphBlock.js (for inserting), but not both simultaneously.
- Prevent Multiple Insertions: Ensure that a block is inserted only once at the intended position.
-
Detailed Implementation:
1. Update Graph.js to Handle Appending
Ensure that the Graph.js component still acts as a drop target for appending blocks when they're dropped outside any existing GraphBlock.
// Graph.js
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) => {
// Only append if not handled by GraphBlock
if (!monitor.didDrop()) {
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:
monitor.didDrop() is used to check if the drop has already been handled by a nested drop target (i.e., a GraphBlock).
- This ensures that if a
GraphBlock has handled the drop (for insertion), the Graph.js won't append the block again.
2. Refine GraphBlock.js to Handle Insertion
Update the GraphBlock.js component to handle dropping new WORKOUT_BLOCKs before itself.
// 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);
// Update the index for the dragged item
item.index = hoverIndex;
}
if (item.type === 'WORKOUT_BLOCK') {
const hoverIndex = index;
// Determine whether to insert before or after based on mouse position
if (hoverClientX < hoverMiddleX) {
addBlockToGraph(item, hoverIndex);
} else {
addBlockToGraph(item, hoverIndex + 1);
}
// To prevent multiple insertions, set item's type to null after insertion
item.type = null;
}
},
});
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:
- Handling
WORKOUT_BLOCK: When a WORKOUT_BLOCK is hovered over a GraphBlock, it determines whether to insert the new block before or after the current GraphBlock based on the mouse's X position relative to the block's midpoint.
- Preventing Multiple Insertions: After inserting the block, the
item.type is set to null to prevent the hover function from inserting the block multiple times during the same drag action.
- Dynamic Insertion Point: This logic allows the new block to be inserted either before or after the target
GraphBlock, providing flexibility in placement.
3. Optimize GraphBlock.js for Better UX
While the above implementation handles insertion, you might want to provide visual feedback to the user about where the block will be inserted. Here's how you can enhance the GraphBlock.js for better user experience:
// GraphBlock.js
import React, { useRef, useState } from 'react';
import { useDrag, useDrop } from 'react-dnd';
const GraphBlock = ({
id,
index,
block,
moveBlock,
removeBlock,
addBlockToGraph,
totalBlocks,
}) => {
const ref = useRef(null);
const [isOverCurrent, setIsOverCurrent] = useState(false);
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);
// Update the index for the dragged item
item.index = hoverIndex;
}
if (item.type === 'WORKOUT_BLOCK') {
const hoverIndex = index;
// Determine whether to insert before or after based on mouse position
if (hoverClientX < hoverMiddleX) {
addBlockToGraph(item, hoverIndex);
} else {
addBlockToGraph(item, hoverIndex + 1);
}
// Prevent multiple insertions
item.type = null;
}
},
collect: (monitor) => {
const isOver = monitor.isOver({ shallow: true });
setIsOverCurrent(isOver);
return {};
},
});
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 transition-all duration-200
${isOverCurrent ? 'border-2 border-blue-500' : ''}
`}
style={{
width: `calc(${100 / totalBlocks}% - 8px)`, // Even width distribution
height: `${block.height}%`,
marginRight: index !== totalBlocks - 1 ? '8px' : '0',
opacity: isDragging ? 0.5 : 1,
}}
>
{/* 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;
Enhancements:
- Visual Feedback: When a
GraphBlock is hovered over by a WORKOUT_BLOCK, a border appears around it to indicate that the block will be inserted here.
- Smooth Transitions: Added transition effects for better visual appeal.
4. Ensure addBlockToGraph Prevents Duplicate Insertions
Modify the addBlockToGraph function in App.js to prevent duplicate insertions when a block is already being added.
// 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
const addingRef = useRef(false); // To prevent multiple additions
// Function to add a new block to the Graph at a specific index
const addBlockToGraph = useCallback((block, index = graphBlocks.length) => {
if (!block || !block.type || typeof block.height !== 'number') {
console.error('Invalid block:', block);
return;
}
// Prevent multiple insertions
if (addingRef.current) return;
addingRef.current = true;
const newBlock = { ...block, id: idRef.current++ };
setGraphBlocks((prevBlocks) => {
const updatedBlocks = [...prevBlocks];
updatedBlocks.splice(index, 0, newBlock);
return updatedBlocks;
});
// Reset the flag after the update
setTimeout(() => {
addingRef.current = false;
}, 0);
}, [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:
addingRef: A mutable ref to prevent multiple insertions during the same drag action. This ensures that a WORKOUT_BLOCK is added only once even if the hover event is triggered multiple times rapidly.
5. Update WorkoutBlocks.js to Ensure Proper Drag Data
Ensure that the WorkoutBlock component provides the necessary data when being dragged.
// 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 Graph.js and GraphBlock.js
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 Consistent Drag Data: The
WorkoutBlock component provides the type and height when being dragged, which are essential for creating new blocks in the graph.
6. Final Touches and Testing
After implementing the above changes, perform thorough testing to ensure:
-
Dragging a WORKOUT_BLOCK Over the Graph:
- If it's not over any existing
GraphBlock, it should append to the end.
- If it's over an existing
GraphBlock, it should insert before or after based on the drop position.
-
Rearranging Existing GraphBlocks:
- Dragging a
GraphBlock over another should rearrange their order accordingly.
-
Removing Blocks:
- Clicking the remove button (
×) should remove the respective block from the graph.
-
Preventing Duplicate Insertions:
- Ensure that dragging a
WORKOUT_BLOCK doesn't result in multiple insertions upon quick hovering or dropping.
7. Optional Enhancements
To further improve the user experience, consider implementing the following:
8. Complete Updated Files
For convenience, here are the complete updated files incorporating all the changes:
App.js
// 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
const addingRef = useRef(false); // To prevent multiple additions
// Function to add a new block to the Graph at a specific index
const addBlockToGraph = useCallback((block, index = graphBlocks.length) => {
if (!block || !block.type || typeof block.height !== 'number') {
console.error('Invalid block:', block);
return;
}
// Prevent multiple insertions
if (addingRef.current) return;
addingRef.current = true;
const newBlock = { ...block, id: idRef.current++ };
setGraphBlocks((prevBlocks) => {
const updatedBlocks = [...prevBlocks];
updatedBlocks.splice(index, 0, newBlock);
return updatedBlocks;
});
// Reset the flag after the update
setTimeout(() => {
addingRef.current = false;
}, 0);
}, [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;
Graph.js
// Graph.js
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) => {
// Only append if not handled by GraphBlock
if (!monitor.didDrop()) {
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;
GraphBlock.js
// GraphBlock.js
import React, { useRef, useState } from 'react';
import { useDrag, useDrop } from 'react-dnd';
const GraphBlock = ({
id,
index,
block,
moveBlock,
removeBlock,
addBlockToGraph,
totalBlocks,
}) => {
const ref = useRef(null);
const [isOverCurrent, setIsOverCurrent] = useState(false);
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);
// Update the index for the dragged item
item.index = hoverIndex;
}
if (item.type === 'WORKOUT_BLOCK') {
const hoverIndex = index;
// Determine whether to insert before or after based on mouse position
if (hoverClientX < hoverMiddleX) {
addBlockToGraph(item, hoverIndex);
} else {
addBlockToGraph(item, hoverIndex + 1);
}
// Prevent multiple insertions
item.type = null;
}
},
collect: (monitor) => {
const isOver = monitor.isOver({ shallow: true });
setIsOverCurrent(isOver);
return {};
},
});
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 transition-all duration-200
${isOverCurrent ? 'border-2 border-blue-500' : ''}
`}
style={{
width: `calc(${100 / totalBlocks}% - 8px)`, // Even width distribution
height: `${block.height}%`,
marginRight: index !== totalBlocks - 1 ? '8px' : '0',
opacity: isDragging ? 0.5 : 1,
}}
>
{/* 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;
WorkoutBlocks.js
// 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 Graph.js and GraphBlock.js
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;
ColumnsList.js
(No changes needed, but included for completeness.)
// ColumnsList.js
import React from 'react';
const ColumnsList = ({ blocks }) => {
return (
<div className="mt-4 overflow-y-auto max-h-full bg-white rounded-lg shadow-md p-4">
<h3 className="text-lg font-semibold mb-2">Current Columns</h3>
{blocks.length === 0 ? (
<p className="text-gray-500">No columns added yet.</p>
) : (
<ul className="space-y-2">
{blocks.map((block, index) => (
<li key={block.id} className="flex items-center">
<span className="mr-2 font-medium">Column {index + 1}:</span>
<span>{block.type}</span>
</li>
))}
</ul>
)}
</div>
);
};
export default ColumnsList;
9. Final Notes
- State Management: Ensure that your state management prevents race conditions or unexpected behavior, especially when rapidly dragging and dropping.
- Performance Considerations: For larger graphs, consider optimizing the rendering performance, possibly using
React.memo or other optimization techniques.
- Accessibility: Ensure that the drag-and-drop interactions are accessible, including keyboard navigation and ARIA attributes where necessary.
- Styling: Adjust the styling as per your design requirements to make the interactions intuitive and visually appealing.
By implementing these changes, your application should now support inserting workout blocks anywhere within the graph, providing a more flexible and user-friendly experience.