A dashboard drag should give the same board for the same drop cell, no matter what path the pointer took to get there.

The problem

Most grid layout libraries resolve collisions incrementally as you drag. Each hover pushes tiles around, and the next hover starts from wherever they ended up. So the same drop cell can produce different boards depending on how you wiggled on the way, and dragging back to where you started doesn’t give you your board back.

What I concluded

The layout is a pure function of the board when the drag started and the cell under the pointer now. Reading order decides who yields: tiles above the drop stay above, everything else is pushed below, then gravity closes the gaps.

function applyDrag(start, id, x, y) {
  const held = start.find((t) => t.id === id);
  const item = { ...held, y: Math.max(0, y),
                 x: clamp(x, 0, COLS - held.w) };
  const others = start.filter((t) => t.id !== id)
    .sort((a, b) => a.y - b.y || a.x - b.x);
  const order = [...others.filter((t) => t.y < item.y), item,
                 ...others.filter((t) => t.y >= item.y)];
  const placed = [];
  for (const tile of order) {
    const next = { ...tile };
    while (placed.some((p) => collides(p, next))) next.y++;
    placed.push(next);
  }
  return gravity(placed); // same order, so the held tile wins ties
}

Rules

  • Always start from the start. Never from the previous hover’s result.
  • Reading order decides who yields. Above the drop stays put, the rest moves down.
  • Gravity runs in the same order. The dragged tile wins ties.
  • Dragging isn’t the only way. Each tile is focusable and arrow keys move it through the same function, with the new position announced politely. Because it’s pure, the keyboard path can’t drift from the pointer path.

What you get

A board that behaves like arithmetic. The same drop gives the same result, dragging back undoes the move, and the keyboard and the pointer produce identical layouts.

The demo has both: drag a tile around and back, or focus one and use the arrows. Related: Layout geometry.