Design: Drag and Drop System
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2025-04-23
Problem Statement
Design a Drag and Drop system that can be integrated into applications like dashboards, file managers, or web editors. The focus is on object-oriented design, modularity, event handling, and state management.
✅ Functional Requirements
1.Draggable Components
•Support multiple draggable elements (e.g., files, widgets, UI components).
•Each draggable element has properties: id, position, size, type.
2.Drop Targets
•Define areas where elements can be dropped.
•Support validation rules (e.g., only certain types can be dropped).
3.Drag & Drop Operations
•Initiate drag on mouse/touch start.
•Track element position during drag.
•On drop, validate and update element position/state.
4.Event Handling
•Trigger events: onDragStart, onDrag, onDrop, onDragEnd.
•Allow multiple listeners for each event.
5.Optional Features
•Snap-to-grid or alignment guidelines.
•Animation during drag or drop.
•Multi-select drag and drop.
•Undo/Redo support for drag operations.
🔐 Constraints & Assumptions
•Focus is on LLD and modular design, not rendering or UI implementation.
•Coordinates and positions are 2D Cartesian values.
•System should efficiently handle multiple draggable elements and targets.
🧱 Key Components & Classes
1.DraggableElement Class
1
2class DraggableElement {
3private:
4 string id;
5 int x, y; // current position
6 int width, height;
7 string type;
8public:
9 void startDrag();
10 void updatePosition(int newX, int newY);
11 void endDrag();
12};1.DropTarget Class
1
2class DropTarget {
3private:
4 string id;
5 int x, y, width, height;
6 vector<string> allowedTypes;
7public:
8 bool canAccept(DraggableElement* element);
9 void onDrop(DraggableElement* element);
10};1.DragDropManager Class
1
2class DragDropManager {
3private:
4 vector<DraggableElement*> elements;
5 vector<DropTarget*> targets;
6 DraggableElement* activeElement;
7public:
8 void registerElement(DraggableElement* element);
9 void registerTarget(DropTarget* target);
10 void handleDragStart(string elementId);
11 void handleDragMove(int x, int y);
12 void handleDrop();
13};1.Event System (Optional)
•Allows registering callbacks for onDragStart, onDrag, onDrop, etc.
🔄 Example Workflow
1.User clicks and holds a draggable element → handleDragStart(elementId).
2.Element position updates as mouse moves → handleDragMove(x, y).
3.User releases mouse over a drop target → handleDrop().
4.System validates drop → updates element position → triggers onDrop event.
🧪 Expected Deliverables
•Class diagram showing DraggableElement, DropTarget, and DragDropManager.
•Implementation of drag start, drag move, drop validation, and event triggers.
•Test cases:
•Dragging element within bounds
•Dropping element on valid and invalid targets
•Handling multiple draggable elements
•Optional: snap-to-grid or multi-select drag