bento-grid.tsx 18 KB

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