2022-08-23 23:35:36 +02:00
|
|
|
import { BoxDefinition } from '../types'
|
|
|
|
|
|
2022-08-24 09:45:54 +02:00
|
|
|
/**
|
|
|
|
|
* Makes sure the boxes stick to the top and also that the array
|
|
|
|
|
* is sorted by y coordinate
|
|
|
|
|
*/
|
2022-08-23 23:35:36 +02:00
|
|
|
export function normalizeBoxes(boxes: BoxDefinition[]) {
|
2022-08-24 08:59:18 +02:00
|
|
|
let sorted = false
|
|
|
|
|
|
2022-08-23 23:35:36 +02:00
|
|
|
// TODO: This is not optimized at all
|
2022-08-24 08:59:18 +02:00
|
|
|
while (!sorted) {
|
|
|
|
|
// Sort boxes to have the lowest ones first
|
|
|
|
|
boxes.sort((a, b) => a.y - b.y)
|
|
|
|
|
|
|
|
|
|
sorted = true
|
2022-08-23 23:35:36 +02:00
|
|
|
|
2022-08-24 08:59:18 +02:00
|
|
|
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)
|
2022-08-23 23:35:36 +02:00
|
|
|
|
2022-08-24 08:59:18 +02:00
|
|
|
if (above.length === 0) {
|
|
|
|
|
box.y = 0
|
|
|
|
|
sorted = false
|
|
|
|
|
break
|
|
|
|
|
} else {
|
|
|
|
|
const newY = above[0].h + above[0].y
|
2022-08-23 23:35:36 +02:00
|
|
|
|
2022-08-24 08:59:18 +02:00
|
|
|
if (box.y !== newY) {
|
|
|
|
|
box.y = newY
|
|
|
|
|
sorted = false
|
|
|
|
|
break
|
|
|
|
|
}
|
2022-08-23 23:35:36 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return boxes
|
|
|
|
|
}
|