bento-grid.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. "use client";
  2. import {
  3. useCallback,
  4. useEffect,
  5. useLayoutEffect,
  6. useMemo,
  7. useRef,
  8. useState,
  9. type CSSProperties,
  10. type PointerEvent as ReactPointerEvent,
  11. type ReactNode,
  12. } from "react";
  13. import {
  14. pack,
  15. placeAt,
  16. readingOrder,
  17. sameLayout,
  18. tierFor,
  19. TIERS,
  20. type Cell,
  21. type Size,
  22. } from "@/lib/bento-layout";
  23. import { springs } from "@/lib/motion";
  24. import { prefersReducedMotion } from "@/lib/utils";
  25. import {
  26. isView,
  27. onBeforeViewChange,
  28. setView,
  29. useView,
  30. type View,
  31. } from "@/lib/view-store";
  32. export type BentoItem = {
  33. id: string;
  34. tags: View[];
  35. /** Columns × rows in each layout tier (TIERS): phones, wide phones, small tablets, tablets, desktops. */
  36. size: readonly [Size, Size, Size, Size, Size];
  37. label: string;
  38. content: ReactNode;
  39. /** Skip the entrance animation (keep it off the LCP card). */
  40. still?: boolean;
  41. };
  42. type Drag = {
  43. id: string;
  44. el: HTMLElement;
  45. touch: boolean;
  46. startX: number;
  47. startY: number;
  48. /** Where the card was grabbed, relative to its top-left corner. */
  49. grabX: number;
  50. grabY: number;
  51. /** Latest pointer position (client coordinates). */
  52. x: number;
  53. y: number;
  54. active: boolean;
  55. frame: number;
  56. hold: number;
  57. /** Layout tier and grid metrics, fixed for the life of the drag. */
  58. tier: number;
  59. cols: number;
  60. /** The cell the card was last placed in. */
  61. cell: { x: number; y: number } | null;
  62. /** Reading order when the drag began: the others always re-pack in this order. */
  63. base: string[];
  64. };
  65. // Pointer-downs on these never start a card drag.
  66. const INTERACTIVE =
  67. "a,button,input,textarea,select,label,canvas,[data-nodrag],[contenteditable=true]";
  68. /** Press and hold this long before a touch drag starts (quicker moves scroll). */
  69. const HOLD_MS = 380;
  70. /** Holding a card this close to the top or bottom of the viewport scrolls. */
  71. const EDGE = 72;
  72. /** The spotlight and rim light reach this far from the cursor. */
  73. const LIGHT_REACH = 280;
  74. /** A card's slot in the grid: layout only, untouched by transforms or animations. */
  75. const slotOf = (el: HTMLElement) => ({
  76. left: el.offsetLeft,
  77. top: el.offsetTop,
  78. width: el.offsetWidth,
  79. height: el.offsetHeight,
  80. });
  81. /** Keep the dragged card under the pointer, wherever its slot is now. */
  82. function glue(grid: HTMLElement, d: Drag) {
  83. const g = grid.getBoundingClientRect();
  84. const s = slotOf(d.el);
  85. d.el.style.transform = `translate3d(${d.x - g.left - d.grabX - s.left}px, ${d.y - g.top - d.grabY - s.top}px, 0)`;
  86. }
  87. export function BentoGrid({ items }: { items: BentoItem[] }) {
  88. const view = useView();
  89. const [order, setOrder] = useState(() => items.map((i) => i.id));
  90. const byId = useMemo(
  91. () => new Map(items.map((i, n) => [i.id, { ...i, n }])),
  92. [items],
  93. );
  94. const display = useMemo(() => {
  95. if (view === "all") return order;
  96. const hit = (id: string) => byId.get(id)?.tags.includes(view);
  97. return [...order.filter(hit), ...order.filter((id) => !hit(id))];
  98. }, [order, view, byId]);
  99. // Layouts the visitor arranged by dragging, per view and tier.
  100. const [custom, setCustom] = useState<Record<string, Cell[]>>({});
  101. const [ghost, setGhost] = useState<Cell | null>(null);
  102. const layouts = useMemo(
  103. () =>
  104. TIERS.map(
  105. (t, i) =>
  106. custom[`${view}:${i}`] ??
  107. pack(display, (id) => byId.get(id)?.size[i] ?? [1, 1], t.cols),
  108. ),
  109. [custom, display, view, byId],
  110. );
  111. const wrapRef = useRef<HTMLDivElement>(null);
  112. const gridRef = useRef<HTMLUListElement>(null);
  113. const nodes = useRef(new Map<string, HTMLElement>());
  114. const before = useRef<Map<string, DOMRect> | null>(null);
  115. const drag = useRef<Drag | null>(null);
  116. const layoutsRef = useRef(layouts);
  117. const byIdRef = useRef(byId);
  118. const viewRef = useRef(view);
  119. const pointer = useRef({
  120. x: 0,
  121. y: 0,
  122. frame: 0,
  123. lit: new Set<HTMLElement>(),
  124. });
  125. useLayoutEffect(() => {
  126. layoutsRef.current = layouts;
  127. byIdRef.current = byId;
  128. viewRef.current = view;
  129. });
  130. const snapshot = useCallback(() => {
  131. const m = new Map<string, DOMRect>();
  132. nodes.current.forEach((el, id) => m.set(id, el.getBoundingClientRect()));
  133. return m;
  134. }, []);
  135. // Measure before the view changes so cards can glide (FLIP) to their new slots.
  136. useEffect(
  137. () =>
  138. onBeforeViewChange(() => {
  139. before.current = snapshot();
  140. }),
  141. [snapshot],
  142. );
  143. useEffect(() => {
  144. const fromHash = () => {
  145. const hash = window.location.hash.slice(1);
  146. setView(isView(hash) ? hash : "all", { updateUrl: false });
  147. };
  148. fromHash();
  149. window.addEventListener("hashchange", fromHash);
  150. return () => window.removeEventListener("hashchange", fromHash);
  151. }, []);
  152. // FLIP: every card that changed slots glides from where it was.
  153. useLayoutEffect(() => {
  154. const first = before.current;
  155. before.current = null;
  156. if (!first) return;
  157. const s = springs.glide();
  158. const still = prefersReducedMotion();
  159. const d = drag.current?.active ? drag.current : null;
  160. nodes.current.forEach((el, id) => {
  161. if (d?.id === id) return;
  162. const a = first.get(id);
  163. if (!a) return;
  164. el.getAnimations().forEach((anim) => anim.id === "flip" && anim.cancel());
  165. if (still) return;
  166. const b = el.getBoundingClientRect();
  167. const dx = a.left - b.left;
  168. const dy = a.top - b.top;
  169. if (Math.abs(dx) < 1 && Math.abs(dy) < 1) return;
  170. const anim = el.animate(
  171. [{ translate: `${dx}px ${dy}px` }, { translate: "0px 0px" }],
  172. { duration: s.duration, easing: s.easing },
  173. );
  174. anim.id = "flip";
  175. });
  176. if (d && gridRef.current) glue(gridRef.current, d);
  177. }, [layouts]);
  178. /* ---------- Drag to rearrange: mouse, pen, or long-press on touch ---------- */
  179. useEffect(() => {
  180. const grid = gridRef.current;
  181. if (!grid) return;
  182. const frame = () => {
  183. const d = drag.current;
  184. if (!d?.active) return;
  185. d.frame = 0;
  186. // Scroll while the card is held near the top or bottom of the viewport.
  187. const near =
  188. d.y < EDGE
  189. ? d.y - EDGE
  190. : d.y > innerHeight - EDGE
  191. ? d.y - (innerHeight - EDGE)
  192. : 0;
  193. if (near) {
  194. window.scrollBy(
  195. 0,
  196. Math.sign(near) * Math.min(22, (near / EDGE) ** 2 * 22),
  197. );
  198. }
  199. glue(grid, d);
  200. // Snap the card's top-left corner to the nearest cell.
  201. const layout = layoutsRef.current[d.tier];
  202. const held = layout.find((c) => c.id === d.id);
  203. if (held) {
  204. const g = grid.getBoundingClientRect();
  205. const gap = parseFloat(getComputedStyle(grid).columnGap) || 0;
  206. const pitch = (g.width + gap) / d.cols;
  207. const x = Math.min(
  208. Math.max(Math.round((d.x - g.left - d.grabX) / pitch), 0),
  209. d.cols - held.w,
  210. );
  211. const y = Math.max(Math.round((d.y - g.top - d.grabY) / pitch), 0);
  212. if (!d.cell || d.cell.x !== x || d.cell.y !== y) {
  213. d.cell = { x, y };
  214. const next = placeAt(
  215. d.base,
  216. (id) => byIdRef.current.get(id)?.size[d.tier] ?? [1, 1],
  217. d.cols,
  218. d.id,
  219. x,
  220. y,
  221. );
  222. if (!sameLayout(next, layout)) {
  223. const key = `${viewRef.current}:${d.tier}`;
  224. before.current = snapshot();
  225. setCustom((c) => ({ ...c, [key]: next }));
  226. if (viewRef.current === "all") setOrder(readingOrder(next));
  227. }
  228. setGhost(next.find((c) => c.id === d.id) ?? null);
  229. }
  230. }
  231. if (near) d.frame = requestAnimationFrame(frame);
  232. };
  233. const activate = (d: Drag) => {
  234. d.active = true;
  235. d.el.removeAttribute("data-pressed");
  236. d.el.getAnimations().forEach((a) => a.cancel());
  237. const r = d.el.getBoundingClientRect();
  238. // Measure the grab point again now that any in-flight animation is gone.
  239. d.grabX = Math.min(Math.max(d.startX - r.left, 0), r.width);
  240. d.grabY = Math.min(Math.max(d.startY - r.top, 0), r.height);
  241. d.base = readingOrder(layoutsRef.current[d.tier]);
  242. d.el.setAttribute("data-dragging", "true");
  243. wrapRef.current?.setAttribute("data-dragging", "true");
  244. setGhost(layoutsRef.current[d.tier].find((c) => c.id === d.id) ?? null);
  245. document.documentElement.style.userSelect = "none";
  246. window.getSelection()?.removeAllRanges();
  247. if (d.touch) navigator.vibrate?.(8);
  248. glue(grid, d);
  249. };
  250. const onMove = (e: PointerEvent) => {
  251. const d = drag.current;
  252. if (!d) return;
  253. d.x = e.clientX;
  254. d.y = e.clientY;
  255. if (!d.active) {
  256. const moved = Math.hypot(d.x - d.startX, d.y - d.startY);
  257. // On touch a quick move is a scroll; with a mouse a small one starts the drag.
  258. if (d.touch) {
  259. if (moved > 10) end();
  260. } else if (moved > 6) {
  261. activate(d);
  262. }
  263. return;
  264. }
  265. if (!d.frame) d.frame = requestAnimationFrame(frame);
  266. };
  267. // Once a touch drag is live, the page must not scroll under the finger.
  268. const blockScroll = (e: TouchEvent) => {
  269. if (drag.current?.active) e.preventDefault();
  270. };
  271. const blockMenu = (e: Event) => {
  272. if (drag.current?.touch) e.preventDefault();
  273. };
  274. const end = () => {
  275. const d = drag.current;
  276. drag.current = null;
  277. window.removeEventListener("pointermove", onMove);
  278. window.removeEventListener("pointerup", end);
  279. window.removeEventListener("pointercancel", end);
  280. window.removeEventListener("touchmove", blockScroll);
  281. window.removeEventListener("contextmenu", blockMenu);
  282. if (!d) return;
  283. window.clearTimeout(d.hold);
  284. cancelAnimationFrame(d.frame);
  285. d.el.removeAttribute("data-pressed");
  286. if (!d.active) return;
  287. document.documentElement.style.userSelect = "";
  288. wrapRef.current?.removeAttribute("data-dragging");
  289. setGhost(null);
  290. const from = d.el.style.transform;
  291. d.el.style.transform = "";
  292. d.el.removeAttribute("data-dragging");
  293. if (!prefersReducedMotion()) {
  294. const s = springs.glide();
  295. d.el.animate([{ transform: from }, { transform: "none" }], {
  296. duration: s.duration,
  297. easing: s.easing,
  298. });
  299. }
  300. // Swallow the click that follows a drag.
  301. const stop = (ev: MouseEvent) => {
  302. ev.stopPropagation();
  303. ev.preventDefault();
  304. };
  305. window.addEventListener("click", stop, { capture: true, once: true });
  306. window.setTimeout(
  307. () => window.removeEventListener("click", stop, { capture: true }),
  308. 0,
  309. );
  310. };
  311. const onDown = (e: PointerEvent) => {
  312. if (drag.current || !e.isPrimary) return;
  313. if (e.pointerType === "mouse" && e.button !== 0) return;
  314. const target = e.target as Element;
  315. if (target.closest(INTERACTIVE)) return;
  316. const el = target.closest<HTMLElement>("[data-card]");
  317. if (!el || !grid.contains(el)) return;
  318. const r = el.getBoundingClientRect();
  319. const d: Drag = {
  320. id: el.dataset.card!,
  321. el,
  322. touch: e.pointerType === "touch",
  323. startX: e.clientX,
  324. startY: e.clientY,
  325. grabX: e.clientX - r.left,
  326. grabY: e.clientY - r.top,
  327. x: e.clientX,
  328. y: e.clientY,
  329. active: false,
  330. frame: 0,
  331. hold: 0,
  332. tier: tierFor(window.innerWidth),
  333. cols: 0,
  334. cell: null,
  335. base: [],
  336. };
  337. d.cols = TIERS[d.tier].cols;
  338. drag.current = d;
  339. el.setAttribute("data-pressed", "");
  340. window.addEventListener("pointermove", onMove, { passive: true });
  341. window.addEventListener("pointerup", end);
  342. window.addEventListener("pointercancel", end);
  343. if (d.touch) {
  344. window.addEventListener("touchmove", blockScroll, { passive: false });
  345. window.addEventListener("contextmenu", blockMenu);
  346. d.hold = window.setTimeout(() => {
  347. if (drag.current === d) activate(d);
  348. }, HOLD_MS);
  349. }
  350. };
  351. grid.addEventListener("pointerdown", onDown);
  352. return () => {
  353. grid.removeEventListener("pointerdown", onDown);
  354. end();
  355. };
  356. }, [snapshot]);
  357. /* ---------- Spotlight + tilt: one listener, only the cards near the cursor ---------- */
  358. const paintSpot = () => {
  359. const p = pointer.current;
  360. p.frame = 0;
  361. if (drag.current?.active) return;
  362. const lit = new Set<HTMLElement>();
  363. nodes.current.forEach((el) => {
  364. const r = el.getBoundingClientRect();
  365. const dx = Math.max(r.left - p.x, 0, p.x - r.right);
  366. const dy = Math.max(r.top - p.y, 0, p.y - r.bottom);
  367. if (Math.hypot(dx, dy) > LIGHT_REACH) return;
  368. lit.add(el);
  369. el.style.setProperty("--mx", `${(p.x - r.left).toFixed(0)}px`);
  370. el.style.setProperty("--my", `${(p.y - r.top).toFixed(0)}px`);
  371. const inside = dx === 0 && dy === 0;
  372. el.style.setProperty(
  373. "--tx",
  374. inside ? (((p.x - r.left) / r.width) * 2 - 1).toFixed(3) : "0",
  375. );
  376. el.style.setProperty(
  377. "--ty",
  378. inside ? (((p.y - r.top) / r.height) * 2 - 1).toFixed(3) : "0",
  379. );
  380. });
  381. // Cards the light just left go dark once, instead of repainting every frame.
  382. p.lit.forEach((el) => {
  383. if (lit.has(el)) return;
  384. el.style.setProperty("--mx", "-999px");
  385. el.style.setProperty("--my", "-999px");
  386. el.style.setProperty("--tx", "0");
  387. el.style.setProperty("--ty", "0");
  388. });
  389. p.lit = lit;
  390. };
  391. const onGridMove = (e: ReactPointerEvent) => {
  392. if (e.pointerType === "touch") return;
  393. const p = pointer.current;
  394. p.x = e.clientX;
  395. p.y = e.clientY;
  396. wrapRef.current?.style.setProperty("--spot", "1");
  397. if (!p.frame) p.frame = requestAnimationFrame(paintSpot);
  398. };
  399. const onGridLeave = () => {
  400. const p = pointer.current;
  401. cancelAnimationFrame(p.frame);
  402. p.frame = 0;
  403. wrapRef.current?.style.setProperty("--spot", "0");
  404. p.lit.forEach((el) => {
  405. el.style.setProperty("--tx", "0");
  406. el.style.setProperty("--ty", "0");
  407. });
  408. };
  409. return (
  410. <div
  411. ref={wrapRef}
  412. className="bento-wrap"
  413. onPointerLeave={onGridLeave}
  414. onPointerMove={onGridMove}
  415. >
  416. <ul ref={gridRef} className="bento">
  417. {/* DOM order never changes (moving nodes would restart their animations
  418. and reload iframes); each card's cell comes from the layout. */}
  419. {items.map(({ id }) => {
  420. const item = byId.get(id);
  421. if (!item) return null;
  422. const dim = view !== "all" && !item.tags.includes(view);
  423. const place: Record<string, number> = { "--i": item.n };
  424. layouts.forEach((layout, t) => {
  425. const c = layout.find((cell) => cell.id === id);
  426. if (!c) return;
  427. place[`--c${t}`] = c.x + 1;
  428. place[`--r${t}`] = c.y + 1;
  429. place[`--w${t}`] = c.w;
  430. place[`--h${t}`] = c.h;
  431. });
  432. return (
  433. <li
  434. key={id}
  435. ref={(el) => {
  436. if (!el) return;
  437. nodes.current.set(id, el);
  438. return () => {
  439. nodes.current.delete(id);
  440. };
  441. }}
  442. aria-label={item.label}
  443. className="card"
  444. data-card={id}
  445. data-dim={dim ? "true" : undefined}
  446. data-enter={item.still ? undefined : ""}
  447. id={`card-${id}`}
  448. style={place as CSSProperties}
  449. >
  450. <div className="card-body">{item.content}</div>
  451. <span aria-hidden className="card-rim" />
  452. </li>
  453. );
  454. })}
  455. {ghost && (
  456. <li
  457. aria-hidden
  458. className="bento-ghost"
  459. style={{
  460. gridColumn: `${ghost.x + 1} / span ${ghost.w}`,
  461. gridRow: `${ghost.y + 1} / span ${ghost.h}`,
  462. }}
  463. />
  464. )}
  465. </ul>
  466. </div>
  467. );
  468. }