Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Maybe fix #2

Open
wants to merge 5 commits into
base: fix-masonry
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 74 additions & 58 deletions packages/mui-lab/src/Masonry/Masonry.js
Original file line number Diff line number Diff line change
Expand Up @@ -182,81 +182,97 @@ const Masonry = React.forwardRef(function Masonry(inProps, ref) {

const classes = useUtilityClasses(ownerState);

React.useEffect(() => {
const handleResize = () => {
const parentWidth = masonryRef.current.clientWidth;
const childWidth = masonryRef.current.firstChild.clientWidth;
const firstChildComputedStyle = window.getComputedStyle(masonryRef.current.firstChild);
const firstChildMarginLeft = parseToNumber(firstChildComputedStyle.marginLeft);
const firstChildMarginRight = parseToNumber(firstChildComputedStyle.marginRight);

if (parentWidth === 0 || childWidth === 0) {
return;
}

const currentNumberOfColumns = Math.round(
parentWidth / (childWidth + firstChildMarginLeft + firstChildMarginRight),
);
const observer = React.useRef(
typeof ResizeObserver === 'undefined'
? undefined
: new ResizeObserver((elements) => {
const masonry = elements[0];
const masonryFirstChild = elements[1];
if (!masonryFirstChild) {
return;
}
const parentWidth = masonry.target.clientWidth;
const childWidth = masonryFirstChild.target.clientWidth;
const firstChildComputedStyle = window.getComputedStyle(masonryFirstChild.target);
const firstChildMarginLeft = parseToNumber(firstChildComputedStyle.marginLeft);
const firstChildMarginRight = parseToNumber(firstChildComputedStyle.marginRight);

if (parentWidth === 0 || childWidth === 0) {
return;
}

const columnHeights = new Array(currentNumberOfColumns).fill(0);
let skip = false;
masonryRef.current.childNodes.forEach((child) => {
if (child.nodeType !== Node.ELEMENT_NODE || child.dataset.class === 'line-break' || skip) {
return;
}
const childComputedStyle = window.getComputedStyle(child);
const childMarginTop = parseToNumber(childComputedStyle.marginTop);
const childMarginBottom = parseToNumber(childComputedStyle.marginBottom);
// if any one of children isn't rendered yet, masonry's height shouldn't be computed yet
const childHeight = parseToNumber(childComputedStyle.height)
? Math.ceil(parseToNumber(childComputedStyle.height)) + childMarginTop + childMarginBottom
: 0;
if (childHeight === 0) {
skip = true;
return;
}
// if there is a nested image that isn't rendered yet, masonry's height shouldn't be computed yet
for (let i = 0; i < child.childNodes.length; i += 1) {
const nestedChild = child.childNodes[i];
if (nestedChild.tagName === 'IMG' && nestedChild.clientHeight === 0) {
skip = true;
break;
const currentNumberOfColumns = Math.round(
parentWidth / (childWidth + firstChildMarginLeft + firstChildMarginRight),
);

const columnHeights = new Array(currentNumberOfColumns).fill(0);
let skip = false;

const childNodes = masonry.target.childNodes;
childNodes.forEach((child) => {
if (
child.nodeType !== Node.ELEMENT_NODE ||
child.dataset.class === 'line-break' ||
skip
) {
return;
}
const childComputedStyle = window.getComputedStyle(child);
const childMarginTop = parseToNumber(childComputedStyle.marginTop);
const childMarginBottom = parseToNumber(childComputedStyle.marginBottom);
// if any one of children isn't rendered yet, masonry's height shouldn't be computed yet
const childHeight = parseToNumber(childComputedStyle.height)
? Math.ceil(parseToNumber(childComputedStyle.height)) +
childMarginTop +
childMarginBottom
: 0;
if (childHeight === 0) {
skip = true;
return;
}
// if there is a nested image that isn't rendered yet, masonry's height shouldn't be computed yet
for (let i = 0; i < child.childNodes.length; i += 1) {
const nestedChild = child.childNodes[i];
if (nestedChild.tagName === 'IMG' && nestedChild.clientHeight === 0) {
skip = true;
break;
}
}
if (!skip) {
// find the current shortest column (where the current item will be placed)
const currentMinColumnIndex = columnHeights.indexOf(Math.min(...columnHeights));
columnHeights[currentMinColumnIndex] += childHeight;
const order = currentMinColumnIndex + 1;
child.style.order = order;
}
});
if (!skip) {
setMaxColumnHeight(Math.max(...columnHeights));
const numOfLineBreaks = currentNumberOfColumns > 0 ? currentNumberOfColumns - 1 : 0;
setNumberOfLineBreaks(numOfLineBreaks);
}
}
if (!skip) {
// find the current shortest column (where the current item will be placed)
const currentMinColumnIndex = columnHeights.indexOf(Math.min(...columnHeights));
columnHeights[currentMinColumnIndex] += childHeight;
const order = currentMinColumnIndex + 1;
child.style.order = order;
}
});
if (!skip) {
setMaxColumnHeight(Math.max(...columnHeights));
const numOfLineBreaks = currentNumberOfColumns > 0 ? currentNumberOfColumns - 1 : 0;
setNumberOfLineBreaks(numOfLineBreaks);
}
};
}),
);

React.useEffect(() => {
// IE and old browsers are not supported
if (typeof ResizeObserver === 'undefined') {
return undefined;
}
const resizeObserver = new ResizeObserver(handleResize);

const container = masonryRef.current;
if (container) {
// only the masonry container and its first child are observed for resizing;
// this might cause unforeseen problems in some use cases;
resizeObserver.observe(container);
observer.current.observe(container);
if (container.firstChild) {
resizeObserver.observe(container.firstChild);
observer.current.observe(container.firstChild);
}
}
return () => {
resizeObserver.disconnect();
observer.current.disconnect();
};
}, [columns, spacing, children]);
}, [columns, spacing, children, observer.current]);

const handleRef = useForkRef(ref, masonryRef);
const lineBreakStyle = {
Expand Down
19 changes: 19 additions & 0 deletions packages/mui-lab/src/Masonry/Masonry.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,25 @@ describe('<Masonry />', () => {
width: `calc(${(100 / columns).toFixed(2)}% - ${theme.spacing(spacing)})`,
});
});

it('should throw console error when children are empty', function test() {
if (!/jsdom/.test(window.navigator.userAgent)) {
this.skip();
}
expect(() => render(<Masonry columns={3} spacing={1} />)).toErrorDev(
'Warning: Failed prop type: The prop `children` is marked as required in `ForwardRef(Masonry)`, but its value is `undefined`.',
);
});

it('should not throw type error when children are empty', function test() {
if (/jsdom/.test(window.navigator.userAgent)) {
this.skip();
}
expect(() => render(<Masonry columns={3} spacing={1} />)).toErrorDev(
'Warning: Failed prop type: The prop `children` is marked as required in `ForwardRef(Masonry)`, but its value is `undefined`.',
);
expect(() => render(<Masonry columns={3} spacing={1} />)).not.to.throw(new TypeError());
});
});

describe('style attribute:', () => {
Expand Down