@bedrock-layout/masonry-grid
Version:
bedrock-layout masonry-grid
103 lines (102 loc) • 2.81 kB
JavaScript
import { Grid as v } from "@bedrock-layout/grid";
import { useTheme as S, getSafeGutter as R } from "@bedrock-layout/spacing-constants";
import { forwardRefWithAs as b, convertToMaybe as x } from "@bedrock-layout/type-utils";
import { useResizeObserver as E } from "@bedrock-layout/use-resize-observer";
import i, { forwardRef as z, Children as d, useState as C, cloneElement as M } from "react";
const P = typeof window == "object" && typeof document == "object" && document.nodeType === 9, G = z(
function({ style: r = {}, ...e }, t) {
return /* @__PURE__ */ i.createElement(
"div",
{
ref: t,
style: { gridRow: "span var(--rows, 1)", ...r },
...e
}
);
}
);
function H({ children: n, gutter: r }) {
const [e, t] = C(1), s = S(), c = E(({ target: o }) => {
t(1);
const l = R(s, r) ?? "1px", f = P ? x(m(l, o)) : 1, h = Math.max(f ?? 1, 1), [y] = Array.from(o.children), g = 1 + Math.min(o.scrollHeight, y.scrollHeight), w = Math.ceil(g / h);
t(w);
});
return /* @__PURE__ */ i.createElement(G, { style: { "--rows": e }, ref: c }, d.map(n, (o) => M(o, {
style: {
display: "block",
blockSize: "100%",
...o.props.style ?? {}
}
})));
}
const j = b(
function({ children: r, style: e = {}, ...t }, s) {
return /* @__PURE__ */ i.createElement(
v,
{
ref: s,
"data-bedrock-masonry-grid": !0,
...t,
style: { gridTemplateRows: "1px", ...e }
},
d.map(r, (c) => /* @__PURE__ */ i.createElement(H, { gutter: t.gutter }, c))
);
}
), a = 96;
function p(n) {
const r = String(n), e = parseFloat(r), [, t] = r.match(/[\d.\-+]*\s*(.*)/) ?? ["", ""];
return [e, t];
}
function m(n, r) {
if (!n) return;
const e = r ?? document.body, t = (n ?? "px").trim().toLowerCase();
switch (t) {
case "vmin":
case "vmax":
case "vh":
case "vw":
case "%":
return;
case "ch":
case "ex":
return I(t, e);
case "em":
return u(e, "font-size");
case "rem":
return u(document.body, "font-size");
case "in":
return a;
case "cm":
return a / 2.54;
case "mm":
return a / 25.4;
case "pt":
return a / 72;
case "pc":
return a / 6;
case "px":
return 1;
default: {
const [s, c] = p(t);
if (isNaN(s)) return;
if (!c) return s;
const o = m(c, r);
return typeof o == "number" ? s * o : void 0;
}
}
}
function u(n, r) {
const [e, t] = p(
getComputedStyle(n).getPropertyValue(r)
);
return e * (m(t, n) ?? 1);
}
function I(n, r) {
const e = document.createElement("div");
e.style.height = "128" + n, r.appendChild(e);
const t = u(e, "height") / 128;
return r.removeChild(e), t;
}
export {
j as MasonryGrid
};