clean up masonry algorithm

This commit is contained in:
Chuck Dries 2022-06-28 21:17:00 -07:00
parent 5ada3c3b0d
commit ad21989140
No known key found for this signature in database
GPG Key ID: A00B7AEAE1DC5BE6

View File

@ -43,50 +43,45 @@ const MasonryGallery = ({
[images] [images]
); );
const rowsByBreakpoint = React.useMemo( const targetAspect = aspectTargetsByBreakpoint[breakpoint];
const rows = React.useMemo(
() => () =>
R.map( R.pipe(
R.pipe( R.reduce(
(targetAspect) => (acc, currentAspect) => {
R.reduce( const currentRow = acc.pop();
(acc, currentAspect) => { const currentDiff = Math.abs(targetAspect - currentRow.aspect);
const currentRow = acc.pop(); const diffIfImageIsAddedToCurrentRow = Math.abs(
const currentDiff = Math.abs(targetAspect - currentRow.aspect); targetAspect - (currentRow.aspect + currentAspect)
const diffIfImageIsAddedToCurrentRow = Math.abs( );
targetAspect - (currentRow.aspect + currentAspect) // add image to current row if it gets us closer to our target aspect ratio
); if (currentDiff > diffIfImageIsAddedToCurrentRow) {
// add image to current row if it gets us closer to our target aspect ratio return [
if (currentDiff > diffIfImageIsAddedToCurrentRow) { ...acc,
return [ {
...acc, aspect: currentRow.aspect + currentAspect,
{ images: currentRow.images + 1,
aspect: currentRow.aspect + currentAspect, startIndex: currentRow.startIndex,
images: currentRow.images + 1, },
startIndex: currentRow.startIndex, ];
}, }
]; return [
} ...acc,
return [ currentRow,
...acc, {
currentRow, aspect: currentAspect,
{ images: 1,
aspect: currentAspect, startIndex: currentRow.startIndex + currentRow.images,
images: 1,
startIndex: currentRow.startIndex + currentRow.images,
},
];
}, },
[{ aspect: 0, startIndex: 0, images: 0 }], ];
aspectRatios },
), [{ aspect: 0, startIndex: 0, images: 0 }]
R.indexBy(R.prop("startIndex")) ),
) R.indexBy(R.prop("startIndex"))
)(aspectTargetsByBreakpoint), )(aspectRatios),
[aspectRatios, aspectTargetsByBreakpoint] [aspectRatios, targetAspect]
); );
const rows = rowsByBreakpoint[breakpoint];
let cursor = 0; let cursor = 0;
return ( return (
<div <div
@ -104,10 +99,11 @@ const MasonryGallery = ({
const rowAspectRatioSum = currentRow.aspect; const rowAspectRatioSum = currentRow.aspect;
const ar = getAspectRatio(image); const ar = getAspectRatio(image);
let width; let width;
let height = `calc(100vw / ${rowAspectRatioSum} - 10px)` let height = `calc(100vw / ${rowAspectRatioSum} - 10px)`;
if (ar === rowAspectRatioSum) { if (rowAspectRatioSum < targetAspect / 2) {
width = `calc(300px * ${ar})`; // incomplete row, render stuff at "ideal" sizes instead of filling width
height = 'unset' width = `calc(100vw / ${targetAspect / ar})`;
height = "unset";
} else { } else {
const widthNumber = ((ar / rowAspectRatioSum) * 100).toFixed(7); const widthNumber = ((ar / rowAspectRatioSum) * 100).toFixed(7);
width = `${widthNumber}%`; width = `${widthNumber}%`;