Switch to inlined ResponsiveMasonry

This commit is contained in:
Kalle 2025-03-13 21:45:39 +02:00
parent a5ee98f7c0
commit 155750c16a
3 changed files with 221 additions and 13 deletions

View File

@ -2,7 +2,6 @@ import { Link } from "@remix-run/react";
import clsx from "clsx";
import * as React from "react";
import { useTranslation } from "react-i18next";
import Masonry, { ResponsiveMasonry } from "react-responsive-masonry";
import { Avatar } from "~/components/Avatar";
import { Button, LinkButton } from "~/components/Button";
import { Dialog } from "~/components/Dialog";
@ -21,6 +20,7 @@ import {
userArtPage,
userPage,
} from "~/utils/urls";
import { ResponsiveMasonry } from "../../../modules/responsive-masonry/components/ResponsiveMasonry";
import { ART_PER_PAGE } from "../art-constants";
import type { ListedArt } from "../art-types";
import { previewUrl } from "../art-utils";
@ -63,18 +63,16 @@ export function ArtGrid({
{bigArt ? (
<BigImageDialog close={() => setBigArtId(null)} art={bigArt} />
) : null}
<ResponsiveMasonry columnsCountBreakPoints={{ 350: 1, 750: 2, 900: 3 }}>
<Masonry gutter="1rem">
{itemsToDisplay.map((art) => (
<ImagePreview
key={art.id}
art={art}
canEdit={canEdit}
enablePreview={enablePreview}
onClick={enablePreview ? () => setBigArtId(art.id) : undefined}
/>
))}
</Masonry>
<ResponsiveMasonry>
{itemsToDisplay.map((art) => (
<ImagePreview
key={art.id}
art={art}
canEdit={canEdit}
enablePreview={enablePreview}
onClick={enablePreview ? () => setBigArtId(art.id) : undefined}
/>
))}
</ResponsiveMasonry>
{!everythingVisible ? (
<Pagination

View File

@ -0,0 +1,170 @@
import React from "react";
interface MasonryProps {
children: React.ReactNode | React.ReactNode[];
columnsCount?: number;
gutter?: string;
className?: string;
style?: React.CSSProperties;
containerTag?: keyof JSX.IntrinsicElements;
itemTag?: keyof JSX.IntrinsicElements;
itemStyle?: React.CSSProperties;
sequential?: boolean;
}
interface MasonryState {
columns: React.ReactNode[][];
childRefs: React.RefObject<HTMLDivElement>[];
hasDistributed: boolean;
children?: React.ReactNode | React.ReactNode[];
}
class Masonry extends React.Component<MasonryProps, MasonryState> {
static defaultProps: Partial<MasonryProps> = {
columnsCount: 3,
gutter: "0",
className: undefined,
style: {},
containerTag: "div",
itemTag: "div",
itemStyle: {},
sequential: false,
};
constructor(props: MasonryProps) {
super(props);
this.state = { columns: [], childRefs: [], hasDistributed: false };
}
componentDidUpdate() {
if (!this.state.hasDistributed && !this.props.sequential) {
this.distributeChildren();
}
}
static getDerivedStateFromProps(props: MasonryProps, state: MasonryState) {
const { children, columnsCount } = props;
const hasColumnsChanged = columnsCount !== state.columns.length;
if (state && children === state.children && !hasColumnsChanged) return null;
return {
...Masonry.getEqualCountColumns(children, columnsCount!),
children,
hasDistributed: false,
};
}
shouldComponentUpdate(nextProps: MasonryProps) {
return (
nextProps.children !== this.state.children ||
nextProps.columnsCount !== this.props.columnsCount
);
}
distributeChildren() {
const { children, columnsCount } = this.props;
const columnHeights = Array(columnsCount!).fill(0);
const isReady = this.state.childRefs.every(
(ref) => ref.current?.getBoundingClientRect().height,
);
if (!isReady) return;
const columns: React.ReactNode[][] = Array.from(
{ length: columnsCount! },
() => [],
);
let validIndex = 0;
React.Children.forEach(children, (child) => {
if (child && React.isValidElement(child)) {
const childHeight =
this.state.childRefs[validIndex].current!.getBoundingClientRect()
.height;
const minHeightColumnIndex = columnHeights.indexOf(
Math.min(...columnHeights),
);
columnHeights[minHeightColumnIndex] += childHeight;
columns[minHeightColumnIndex].push(child);
validIndex++;
}
});
this.setState((p) => ({ ...p, columns, hasDistributed: true }));
}
static getEqualCountColumns(
children: React.ReactNode | React.ReactNode[],
columnsCount: number,
) {
const columns: React.ReactNode[][] = Array.from(
{ length: columnsCount },
() => [],
);
let validIndex = 0;
const childRefs: React.RefObject<HTMLDivElement>[] = [];
React.Children.forEach(children, (child) => {
if (child && React.isValidElement(child)) {
const ref = React.createRef<HTMLDivElement>();
childRefs.push(ref);
columns[validIndex % columnsCount].push(
<div
style={{ display: "flex", justifyContent: "stretch" }}
key={validIndex}
ref={ref}
>
{child}
</div>,
);
validIndex++;
}
});
return { columns, childRefs };
}
renderColumns() {
const { gutter, itemTag, itemStyle } = this.props;
return this.state.columns.map((column, i) =>
React.createElement(
itemTag!,
{
key: i,
style: {
display: "flex",
flexDirection: "column",
justifyContent: "flex-start",
alignContent: "stretch",
flex: 1,
width: 0,
gap: gutter,
...itemStyle,
},
},
column.map((item) => item),
),
);
}
render() {
const { gutter, className, style, containerTag } = this.props;
return React.createElement(
containerTag!,
{
style: {
display: "flex",
flexDirection: "row",
justifyContent: "center",
alignContent: "stretch",
boxSizing: "border-box",
width: "100%",
gap: gutter,
...style,
},
className,
},
this.renderColumns(),
);
}
}
export default Masonry;

View File

@ -0,0 +1,40 @@
// adapted from https://github.com/cedricdelpoux/react-responsive-masonry
import React from "react";
import { createBreakpoint } from "react-use";
import Masonry from "./Masonry";
const COLUMN_COUNTS = {
L: 3,
M: 2,
S: 1,
};
const useBreakpoint = createBreakpoint({ L: 900, M: 750, S: 350 });
const MasonryResponsive = ({
children,
}: { children: React.ReactNode | React.ReactNode[] }) => {
const breakpoint = useBreakpoint() as "L" | "M" | "S";
const columnsCount = COLUMN_COUNTS[breakpoint];
return (
<div>
{React.Children.map(children, (child, index) =>
React.cloneElement(child as React.ReactElement, {
key: index,
columnsCount,
}),
)}
</div>
);
};
export function ResponsiveMasonry({ children }: { children: React.ReactNode }) {
return (
<MasonryResponsive>
<Masonry gutter="1rem">{children}</Masonry>
</MasonryResponsive>
);
}