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. onBeforeViewChange,
  27. setView,
  28. useView,
  29. viewFromHash,
  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. setView(viewFromHash(window.location.hash.slice(1)), {
  168. updateUrl: false,
  169. });
  170. };
  171. fromHash();
  172. window.addEventListener("hashchange", fromHash);
  173. return () => window.removeEventListener("hashchange", fromHash);
  174. }, []);
  175. // FLIP: every card that changed slots glides from where it was.
  176. useLayoutEffect(() => {
  177. const first = before.current;
  178. before.current = null;
  179. if (!first) return;
  180. const s = springs.glide();
  181. const still = prefersReducedMotion();
  182. const d = drag.current?.active ? drag.current : null;
  183. nodes.current.forEach((el, id) => {
  184. if (d?.id === id) return;
  185. const a = first.get(id);
  186. if (!a) return;
  187. el.getAnimations().forEach((anim) => anim.id === "flip" && anim.cancel());
  188. if (still) return;
  189. const b = el.getBoundingClientRect();
  190. const dx = a.left - b.left;
  191. const dy = a.top - b.top;
  192. if (Math.abs(dx) < 1 && Math.abs(dy) < 1) return;
  193. const anim = el.animate(
  194. [{ translate: `${dx}px ${dy}px` }, { translate: "0px 0px" }],
  195. { duration: s.duration, easing: s.easing },
  196. );
  197. anim.id = "flip";
  198. });
  199. if (d && gridRef.current) glue(gridRef.current, d);
  200. }, [layouts]);
  201. /* ---------- Drag to rearrange: mouse, pen, or long-press on touch ---------- */
  202. useEffect(() => {
  203. const grid = gridRef.current;
  204. if (!grid) return;
  205. const frame = () => {
  206. const d = drag.current;
  207. if (!d?.active) return;
  208. d.frame = 0;
  209. // Scroll while the card is held near the top or bottom of the viewport.
  210. const near =
  211. d.y < EDGE
  212. ? d.y - EDGE
  213. : d.y > innerHeight - EDGE
  214. ? d.y - (innerHeight - EDGE)
  215. : 0;
  216. if (near) {
  217. window.scrollBy(
  218. 0,
  219. Math.sign(near) * Math.min(22, (near / EDGE) ** 2 * 22),
  220. );
  221. }
  222. glue(grid, d);
  223. // Snap the card's top-left corner to the nearest cell.
  224. const layout = layoutsRef.current[d.tier];
  225. const held = layout.find((c) => c.id === d.id);
  226. if (held) {
  227. const g = grid.getBoundingClientRect();
  228. const gap = parseFloat(getComputedStyle(grid).columnGap) || 0;
  229. const pitch = (g.width + gap) / d.cols;
  230. const x = Math.min(
  231. Math.max(Math.round((d.x - g.left - d.grabX) / pitch), 0),
  232. d.cols - held.w,
  233. );
  234. const y = Math.max(
  235. Math.round((d.y - g.top - d.top - d.grabY) / pitch),
  236. 0,
  237. );
  238. if (!d.cell || d.cell.x !== x || d.cell.y !== y) {
  239. d.cell = { x, y };
  240. const next = placeAt(
  241. d.base,
  242. (id) => byIdRef.current.get(id)?.size[d.tier] ?? [1, 1],
  243. d.cols,
  244. d.id,
  245. x,
  246. y,
  247. );
  248. if (!sameLayout(next, layout)) {
  249. const key = `${viewRef.current}:${d.tier}`;
  250. before.current = snapshot();
  251. setCustom((c) => ({ ...c, [key]: next }));
  252. if (viewRef.current === "all") {
  253. // The new reading order, with any header card kept in its place.
  254. const packed = new Set(next.map((c) => c.id));
  255. const rest = readingOrder(next);
  256. setOrder((o) =>
  257. o.map((id) => (packed.has(id) ? rest.shift()! : id)),
  258. );
  259. }
  260. }
  261. setGhost(ghostOf(d, next));
  262. }
  263. }
  264. if (near) d.frame = requestAnimationFrame(frame);
  265. };
  266. const activate = (d: Drag) => {
  267. d.active = true;
  268. d.el.removeAttribute("data-pressed");
  269. d.el.getAnimations().forEach((a) => a.cancel());
  270. const r = d.el.getBoundingClientRect();
  271. // Measure the grab point again now that any in-flight animation is gone.
  272. d.grabX = Math.min(Math.max(d.startX - r.left, 0), r.width);
  273. d.grabY = Math.min(Math.max(d.startY - r.top, 0), r.height);
  274. d.base = readingOrder(layoutsRef.current[d.tier]);
  275. // On phones the packed cards start below the header row (or its gap, when hidden).
  276. if (d.shift) {
  277. const header = grid.querySelector<HTMLElement>(
  278. ":scope > [data-header]",
  279. );
  280. d.top =
  281. (header?.offsetHeight ?? 0) +
  282. (parseFloat(getComputedStyle(grid).rowGap) || 0);
  283. }
  284. d.el.setAttribute("data-dragging", "true");
  285. wrapRef.current?.setAttribute("data-dragging", "true");
  286. setGhost(ghostOf(d, layoutsRef.current[d.tier]));
  287. document.documentElement.style.userSelect = "none";
  288. window.getSelection()?.removeAllRanges();
  289. if (d.touch) navigator.vibrate?.(8);
  290. glue(grid, d);
  291. };
  292. const onMove = (e: PointerEvent) => {
  293. const d = drag.current;
  294. if (!d) return;
  295. d.x = e.clientX;
  296. d.y = e.clientY;
  297. if (!d.active) {
  298. const moved = Math.hypot(d.x - d.startX, d.y - d.startY);
  299. // On touch a quick move is a scroll; with a mouse a small one starts the drag.
  300. if (d.touch) {
  301. if (moved > 10) end();
  302. } else if (moved > 6) {
  303. activate(d);
  304. }
  305. return;
  306. }
  307. if (!d.frame) d.frame = requestAnimationFrame(frame);
  308. };
  309. // Once a touch drag is live, the page must not scroll under the finger.
  310. const blockScroll = (e: TouchEvent) => {
  311. if (drag.current?.active) e.preventDefault();
  312. };
  313. const blockMenu = (e: Event) => {
  314. if (drag.current?.touch) e.preventDefault();
  315. };
  316. const end = () => {
  317. const d = drag.current;
  318. drag.current = null;
  319. window.removeEventListener("pointermove", onMove);
  320. window.removeEventListener("pointerup", end);
  321. window.removeEventListener("pointercancel", end);
  322. window.removeEventListener("touchmove", blockScroll);
  323. window.removeEventListener("contextmenu", blockMenu);
  324. if (!d) return;
  325. window.clearTimeout(d.hold);
  326. cancelAnimationFrame(d.frame);
  327. d.el.removeAttribute("data-pressed");
  328. if (!d.active) return;
  329. document.documentElement.style.userSelect = "";
  330. wrapRef.current?.removeAttribute("data-dragging");
  331. setGhost(null);
  332. const from = d.el.style.transform;
  333. d.el.style.transform = "";
  334. d.el.removeAttribute("data-dragging");
  335. if (!prefersReducedMotion()) {
  336. const s = springs.glide();
  337. d.el.animate([{ transform: from }, { transform: "none" }], {
  338. duration: s.duration,
  339. easing: s.easing,
  340. });
  341. }
  342. // Swallow the click that follows a drag.
  343. const stop = (ev: MouseEvent) => {
  344. ev.stopPropagation();
  345. ev.preventDefault();
  346. };
  347. window.addEventListener("click", stop, { capture: true, once: true });
  348. window.setTimeout(
  349. () => window.removeEventListener("click", stop, { capture: true }),
  350. 0,
  351. );
  352. };
  353. const onDown = (e: PointerEvent) => {
  354. if (drag.current || !e.isPrimary) return;
  355. if (e.pointerType === "mouse" && e.button !== 0) return;
  356. const target = e.target as Element;
  357. if (target.closest(INTERACTIVE)) return;
  358. const el = target.closest<HTMLElement>("[data-card]");
  359. if (!el || !grid.contains(el)) return;
  360. const tier = tierFor(window.innerWidth);
  361. // A phone header is a fixed row, not a card to move.
  362. if (tier === HEADER_TIER && el.hasAttribute("data-header")) return;
  363. const r = el.getBoundingClientRect();
  364. const d: Drag = {
  365. id: el.dataset.card!,
  366. el,
  367. touch: e.pointerType === "touch",
  368. startX: e.clientX,
  369. startY: e.clientY,
  370. grabX: e.clientX - r.left,
  371. grabY: e.clientY - r.top,
  372. x: e.clientX,
  373. y: e.clientY,
  374. active: false,
  375. frame: 0,
  376. hold: 0,
  377. tier,
  378. cols: 0,
  379. cell: null,
  380. base: [],
  381. shift:
  382. tier === HEADER_TIER && grid.hasAttribute("data-has-header") ? 1 : 0,
  383. top: 0,
  384. };
  385. d.cols = TIERS[d.tier].cols;
  386. drag.current = d;
  387. el.setAttribute("data-pressed", "");
  388. window.addEventListener("pointermove", onMove, { passive: true });
  389. window.addEventListener("pointerup", end);
  390. window.addEventListener("pointercancel", end);
  391. if (d.touch) {
  392. window.addEventListener("touchmove", blockScroll, { passive: false });
  393. window.addEventListener("contextmenu", blockMenu);
  394. d.hold = window.setTimeout(() => {
  395. if (drag.current === d) activate(d);
  396. }, HOLD_MS);
  397. }
  398. };
  399. grid.addEventListener("pointerdown", onDown);
  400. return () => {
  401. grid.removeEventListener("pointerdown", onDown);
  402. end();
  403. };
  404. }, [snapshot]);
  405. /* ---------- Spotlight + tilt: one listener, only the cards near the cursor ---------- */
  406. const paintSpot = () => {
  407. const p = pointer.current;
  408. p.frame = 0;
  409. if (drag.current?.active) return;
  410. const lit = new Set<HTMLElement>();
  411. nodes.current.forEach((el) => {
  412. const r = el.getBoundingClientRect();
  413. const dx = Math.max(r.left - p.x, 0, p.x - r.right);
  414. const dy = Math.max(r.top - p.y, 0, p.y - r.bottom);
  415. if (Math.hypot(dx, dy) > LIGHT_REACH) return;
  416. lit.add(el);
  417. el.style.setProperty("--mx", `${(p.x - r.left).toFixed(0)}px`);
  418. el.style.setProperty("--my", `${(p.y - r.top).toFixed(0)}px`);
  419. const inside = dx === 0 && dy === 0;
  420. el.style.setProperty(
  421. "--tx",
  422. inside ? (((p.x - r.left) / r.width) * 2 - 1).toFixed(3) : "0",
  423. );
  424. el.style.setProperty(
  425. "--ty",
  426. inside ? (((p.y - r.top) / r.height) * 2 - 1).toFixed(3) : "0",
  427. );
  428. });
  429. // Cards the light just left go dark once, instead of repainting every frame.
  430. p.lit.forEach((el) => {
  431. if (lit.has(el)) return;
  432. el.style.setProperty("--mx", "-999px");
  433. el.style.setProperty("--my", "-999px");
  434. el.style.setProperty("--tx", "0");
  435. el.style.setProperty("--ty", "0");
  436. });
  437. p.lit = lit;
  438. };
  439. const onGridMove = (e: ReactPointerEvent) => {
  440. if (e.pointerType === "touch") return;
  441. const p = pointer.current;
  442. p.x = e.clientX;
  443. p.y = e.clientY;
  444. wrapRef.current?.style.setProperty("--spot", "1");
  445. if (!p.frame) p.frame = requestAnimationFrame(paintSpot);
  446. };
  447. const onGridLeave = () => {
  448. const p = pointer.current;
  449. cancelAnimationFrame(p.frame);
  450. p.frame = 0;
  451. wrapRef.current?.style.setProperty("--spot", "0");
  452. p.lit.forEach((el) => {
  453. el.style.setProperty("--tx", "0");
  454. el.style.setProperty("--ty", "0");
  455. });
  456. };
  457. return (
  458. <div
  459. ref={wrapRef}
  460. className="bento-wrap"
  461. onPointerLeave={onGridLeave}
  462. onPointerMove={onGridMove}
  463. >
  464. <ul
  465. ref={gridRef}
  466. className="bento"
  467. data-has-header={hasHeader ? "" : undefined}
  468. >
  469. {/* DOM order never changes (moving nodes would restart their animations
  470. and reload iframes); each card's cell comes from the layout. */}
  471. {items.map(({ id }) => {
  472. const item = byId.get(id);
  473. if (!item) return null;
  474. const dim = view !== "all" && !item.tags.includes(view);
  475. const place: Record<string, number> = { "--i": item.n };
  476. layouts.forEach((layout, t) => {
  477. const c = layout.find((cell) => cell.id === id);
  478. if (!c) return;
  479. // Under a phone header row the cards start one row down.
  480. const shift = t === HEADER_TIER && hasHeader ? 1 : 0;
  481. place[`--c${t}`] = c.x + 1;
  482. place[`--r${t}`] = c.y + 1 + shift;
  483. place[`--w${t}`] = c.w;
  484. place[`--h${t}`] = c.h;
  485. });
  486. if (item.header) {
  487. place[`--c${HEADER_TIER}`] = 1;
  488. place[`--r${HEADER_TIER}`] = 1;
  489. place[`--w${HEADER_TIER}`] = TIERS[HEADER_TIER].cols;
  490. place[`--h${HEADER_TIER}`] = 1;
  491. }
  492. return (
  493. <li
  494. key={id}
  495. ref={(el) => {
  496. if (!el) return;
  497. nodes.current.set(id, el);
  498. return () => {
  499. nodes.current.delete(id);
  500. };
  501. }}
  502. aria-label={item.label}
  503. className="card"
  504. data-card={id}
  505. data-dim={dim ? "true" : undefined}
  506. data-header={item.header ? "" : undefined}
  507. data-enter={item.still ? undefined : ""}
  508. id={`card-${id}`}
  509. style={place as CSSProperties}
  510. >
  511. <div className="card-body">{item.content}</div>
  512. <span aria-hidden className="card-rim" />
  513. </li>
  514. );
  515. })}
  516. {ghost && (
  517. <li
  518. aria-hidden
  519. className="bento-ghost"
  520. style={{
  521. gridColumn: `${ghost.x + 1} / span ${ghost.w}`,
  522. gridRow: `${ghost.y + 1} / span ${ghost.h}`,
  523. }}
  524. />
  525. )}
  526. </ul>
  527. </div>
  528. );
  529. }