-
Notifications
You must be signed in to change notification settings - Fork 10
/
Plock.js
97 lines (82 loc) · 2.38 KB
/
Plock.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import * as React from "react";
const uuid = () => Math.random().toString(36).substring(2, 12);
/**
* Configuration for Plock.
* This is a map of breakpoints to the number of columns to use for that breakpoint.
*
* const breakpoints = [
* { size: 640, columns: 1 },
* { size: 768, columns: 2 },
* { size: 1024, columns: 3 },
* { size: 1280, columns: 4 },
* ];
*/
export function useWindowWidth() {
const [width, setWidth] = React.useState(window.innerWidth);
React.useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return width;
}
export function Plock({ children, className, style, nColumns = 3, gap = 10 }) {
const width = useWindowWidth();
const [columns, setColumns] = React.useState([]);
React.useLayoutEffect(() => {
let columnsElements = [];
if (typeof nColumns === "number") {
columnsElements = Array.from({ length: nColumns }, (e) => []);
} else {
let breakpoint = nColumns
.filter((el) => el.size <= width)
.sort((a, b) => a.size - b.size)
.pop();
if (!breakpoint) {
breakpoint = nColumns.sort((a, b) => a.size - b.size)[0];
}
columnsElements = Array.from({ length: breakpoint.columns }, (e) => []);
}
React.Children.forEach(children, (child, index) => {
const key = uuid();
const cloned = React.cloneElement(child, {
...child.props,
key: key,
});
columnsElements[index % columnsElements.length].push(cloned);
});
setColumns(columnsElements);
}, [children, nColumns, setColumns, width]);
const defaultStyles = {
mainGrid: {
display: "grid",
gridTemplateColumns: `repeat(${columns.length}, 1fr)`,
columnGap: gap,
alignItems: "start",
},
columnGrid: {
display: "grid",
gridTemplateColumns: "100%",
rowGap: gap,
},
};
return (
<div
data-testid="plock-container"
className={className}
style={{ style, ...defaultStyles.mainGrid }}
>
{columns.map((column, index) => {
return (
<div
data-testid="plock-column"
style={defaultStyles.columnGrid}
key={index}
>
{column}
</div>
);
})}
</div>
);
}