# React Grid Layout - Enhanced Collision Handling

This is a modified version of [react-grid-layout](https://github.com/react-grid-layout/react-grid-layout) with enhanced collision handling and smart positioning features.

## Key Modifications

### Smart Collision Handling

When dragging elements in the grid, this modified version implements intelligent collision resolution that:

1. **Detects collision patterns**: When an element is dropped and causes other elements to be pushed down
2. **Attempts gap reduction**: If elements were pushed down by exactly one grid unit, it tries to move them back up
3. **Recursive positioning**: Uses a recursive algorithm to optimally position multiple affected elements
4. **Prevents infinite loops**: Includes safety mechanisms to prevent infinite recursion

### Core Changes

#### 1. New Function: `recursivelyMoveItemsUp`

Located in `lib/utils.js`, this function:
- Finds items below a moved element that are within the collision area
- Attempts to move each item up as far as possible without causing new collisions
- Recursively applies this logic to items that get moved
- Includes iteration limits to prevent infinite loops

#### 2. Enhanced `onDragStop` Method

Modified in `lib/ReactGridLayout.jsx` to:
- Save the layout state before applying moves
- Apply standard collision resolution
- Check for elements that were pushed down by exactly 1 unit
- Apply the smart positioning algorithm to reduce gaps

### Technical Implementation

```javascript
// New function in utils.js
export function recursivelyMoveItemsUp(l: LayoutItem, layout: Layout, iteration: number = 0) {
  if (iteration > 6) return; // prevent infinite loops
  
  const itemsBelow = layout.filter(el => 
    el.y < l.y + l.h + 5 && 
    el.y >= l.y + l.h && 
    ((l.x >= el.x && l.x <= el.x + el.w) || (el.x >= l.x && el.x <= l.x + l.w))
  );
  
  itemsBelow.forEach(el => {
    let prevY = el.y;
    for (let i = 0; i < l.h; i++) {
      el.y = el.y - 1;
      let collidingEl = getFirstCollision(layout, el);
      if (collidingEl) {
        el.y = prevY;
        break;
      }
      prevY = el.y;
    }
    recursivelyMoveItemsUp(el, layout, iteration + 1);
  });
}
```

### Usage

This package can be used as a drop-in replacement for react-grid-layout:

```bash
npm install react-grid-layout-collision-handling
```

```javascript
import { ReactGridLayout } from 'react-grid-layout-collision-handling';
// Use exactly like the original react-grid-layout
```

### Benefits

- **Reduced gaps**: Elements automatically position themselves to minimize empty space
- **Better UX**: More intuitive drag-and-drop behavior
- **Maintains performance**: Efficient algorithms with safety bounds
- **Backward compatible**: Works with existing react-grid-layout code

### Original License

This work is based on react-grid-layout by Samuel Reed, licensed under MIT License.

### Modifications License

Additional modifications are also licensed under MIT License. 