Skip to content

Commit

Permalink
feat: hard-code optimal masonry layout
Browse files Browse the repository at this point in the history
  • Loading branch information
Azganoth committed Aug 13, 2023
1 parent 9b87d22 commit 42eac94
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
24 changes: 23 additions & 1 deletion app/_components/Masonry.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
} from 'react';
import styles from './Masonry.module.css';
import { useMediaQuery } from '@/_hooks/useMediaQuery';
import swapInPlace from '@/_utils/swapInPlace';

function MasonryItem({
children,
Expand Down Expand Up @@ -58,11 +59,32 @@ function MasonryItem({
const MemoizedMasonryItem = memo(MasonryItem);

export default function Masonry({ children }: { children: React.ReactNode }) {
const items = useMemo(() => Children.toArray(children), [children]);
const _items = useMemo(() => Children.toArray(children), [children]);

const isTablet = useMediaQuery('(min-width: 768px)');
const isDesktop = useMediaQuery('(min-width: 1440px)');

// hard code partitioning
const items = useMemo(() => {
const sortedItems = [..._items];
if (isDesktop) {
swapInPlace(sortedItems, 5, 7);
swapInPlace(sortedItems, 8, 10);
swapInPlace(sortedItems, 9, 10);
swapInPlace(sortedItems, 11, 13);
swapInPlace(sortedItems, 12, 13);
swapInPlace(sortedItems, 12, 14);
return sortedItems;
}

if (isTablet) {
swapInPlace(sortedItems, 8, 9);
return sortedItems;
}

return sortedItems;
}, [_items, isTablet, isDesktop]);

const [columns, gap] = useMemo(() => {
if (isDesktop) {
return [4, 40];
Expand Down
5 changes: 5 additions & 0 deletions app/_utils/swapInPlace.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default function swapInPlace(arr: unknown[], i1: number, i2: number) {
const tmp = arr[i1];
arr[i1] = arr[i2];
arr[i2] = tmp;
}

0 comments on commit 42eac94

Please sign in to comment.