Last active
October 30, 2023 14:40
-
-
Save akbarjondev/1338bb30594d61823ecf8c01d6c27fe2 to your computer and use it in GitHub Desktop.
Function returns an array of objects which are used to fill white gaps which are created by Muuri (grid) package
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Grid from 'muuri' | |
interface GapFillerProps { | |
height: number | |
columnId: number | |
gapHeight?: number | |
} | |
export const calculateGaps = (grid: Grid): GapFillerProps[] => { | |
if (!grid) return [] | |
const items = grid.getItems() | |
const lastItems: { [key: number]: HTMLElement } = {} | |
const allColumns: { [key: number]: HTMLElement[] } = {} | |
const columnHeights: { | |
[key: number]: GapFillerProps | |
} = {} | |
// Loop through each item | |
items.forEach((item) => { | |
const rect = item.getElement()?.getBoundingClientRect() | |
const col = Math.round(rect?.left || 0) // Get the left position to represent the column | |
// get all columns | |
if (!allColumns[col]) { | |
allColumns[col] = [item.getElement() as HTMLElement] | |
} else { | |
allColumns[col].push(item.getElement() as HTMLElement) | |
} | |
// If there's no known last item for this column or this item is below the known last item, update it | |
if ( | |
!lastItems[col] || | |
lastItems[col].getBoundingClientRect().bottom < (rect?.bottom || 0) | |
) { | |
if (item.getElement()) { | |
lastItems[col] = item.getElement() as HTMLElement | |
} | |
} | |
// get the height and id of each column | |
if (!columnHeights[col]) { | |
columnHeights[col] = { | |
height: rect?.height || 0, | |
columnId: col, | |
} | |
} else { | |
columnHeights[col].height += rect?.height || 0 | |
} | |
}) | |
// sort columnHeights to get the biggest height | |
const sortedHeights = Object.values(columnHeights).sort((a, b) => { | |
return a.height - b.height | |
}) | |
// get the biggest height | |
const bigHeight = sortedHeights[sortedHeights.length - 1] | |
// calculate the gap height for each column | |
sortedHeights.forEach((column) => { | |
column.gapHeight = bigHeight.height - column.height | |
}) | |
return sortedHeights | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment