bento-grid.tsx 18 KB

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