import { BoxDefinition } from '../types' /** * Makes sure the boxes stick to the top and also that the array * is sorted by y coordinate */ export function normalizeBoxes(boxes: BoxDefinition[]) { let sorted = false // TODO: This is not optimized at all while (!sorted) { // Sort boxes to have the lowest ones first boxes.sort((a, b) => a.y - b.y) sorted = true for (const box of boxes) { if (box.y > 0) { const above = boxes .filter( (b) => b.id !== box.id && b.x < box.x + box.w && box.x < b.x + b.w && b.y < box.y ) .sort((a, b) => b.y - a.y) if (above.length === 0) { box.y = 0 sorted = false break } else { const newY = above[0].h + above[0].y if (box.y !== newY) { box.y = newY sorted = false break } } } } } return boxes }