bento-grid.tsx 18 KB

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