Skip to content

Instantly share code, notes, and snippets.

@mehmetyilmaz001
Created May 23, 2022 12:57
Show Gist options
  • Save mehmetyilmaz001/fb69a65bec18133cb21d65af64a870ff to your computer and use it in GitHub Desktop.
Save mehmetyilmaz001/fb69a65bec18133cb21d65af64a870ff to your computer and use it in GitHub Desktop.
Remove empty rows helper function for react grid layout
/**
* Fix layout by removing the empty rows
* @param {array} layout
* @returns array layout
*/
export const _removeEmptyRowsFromLayout = layout => {
// Find the max Y coordinate which an item reached (The last row num)
const maxY = Math.max(...layout.map(i => i.y));
const emptyRows = [];
// Select items by row with considering heights
const itemSelector = (item, index) => {
const h = item.h < 1 ? 1 : item.h;
const { y } = item;
return index >= y && index <= y + h - 1;
};
// Find the empty rows
for (let i = 0; i <= maxY; i += 1) {
const itemsPerRow = layout.filter(item => itemSelector(item, i));
// If there is no items in a row
if (itemsPerRow.length === 0) {
emptyRows.push(i);
}
}
// Begin from the bottom rows
emptyRows.reverse();
let updatedLayout = [...layout];
// The row after the empty row to begin shifting
const upperRow = emptyRows[0] + 1;
// Move the items to the empty rows
while (emptyRows.length > 0) {
updatedLayout = layout.map(i => {
// If there are items on the upper row
// Set thier y to empty rows y for moving up
if (i.y === upperRow) {
return {
...i,
y: emptyRows[0]
};
}
return i;
});
// Remove the filled row
emptyRows.shift();
}
return updatedLayout;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment