Created
October 7, 2020 21:46
-
-
Save baktun14/cd7d68f29a4c876b6cfd72f32f34ae90 to your computer and use it in GitHub Desktop.
I found that all the masonry libraries were slow so I made my own one.
This file contains 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
/** | |
* The code won't work by it self but most of the logic is here | |
* I was using immutablejs | |
* Also, I'm aware this is not react, but it's code that I'm most proud of 😅 | |
*/ | |
export function getLooksMasonry(masonry: List<List<Map<string, any>>>, lookIds: List<any>, colWidth: number, gutterPadding: number = 5, footerHeight: number = 55) { | |
return (dispatch, getState: () => IGlobalState) => { | |
const { looks } = getState(); | |
return masonry.withMutations(mLayout => { | |
const insertInMasonry = (look: Map<string, any>) => { | |
// find in which column we will insert the new look | |
const computeColHeight = col => col.isEmpty() ? 0 : col.last().get("top") + col.last().get("postHeight"); | |
const shortestCol = mLayout.minBy(col => computeColHeight(col)); | |
const colIndex = mLayout.indexOf(shortestCol); | |
const currentLast = shortestCol.last(); | |
mLayout = mLayout.update(colIndex, (col: List<Map<string, any>>) => { | |
const newBlock = look.merge({ | |
colIndex: colIndex, | |
top: currentLast ? (currentLast.get("top") + currentLast.get("postHeight")) : 0, | |
left: colIndex * colWidth | |
}); | |
return col.push(newBlock); | |
}).toList(); | |
} | |
lookIds.forEach((lookId, i) => { | |
const look = looks.get(lookId); | |
if (look) { | |
const ratio = 3 / 2; | |
const padding = gutterPadding; | |
const postImageHeight = Math.ceil((colWidth - padding) * ratio); | |
const postHeight = postImageHeight + padding + footerHeight; | |
insertInMasonry(Map({ | |
id: lookId, | |
postHeight, | |
postWidth: colWidth, | |
postImageHeight | |
})); | |
} | |
}); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment