hero-title.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. "use client";
  2. import { useEffect, useRef, useState } from "react";
  3. import {
  4. buildLensMap,
  5. supportsBackdropRefraction,
  6. type LensMap,
  7. } from "@/components/glass/displacement";
  8. import { GlassFilter, registerLight } from "@/components/glass/liquid-glass";
  9. import { cn, prefersReducedMotion } from "@/lib/utils";
  10. const LEAD = "Hey, I'm ";
  11. const NAME = "Eric";
  12. const TEXT = `${LEAD}${NAME}.`;
  13. const BASE_WEIGHT = 640;
  14. /** At rest the letters are fully soft; the wave sharpens what it passes and melts what it touches. */
  15. const REST = { fontWeight: BASE_WEIGHT, fontVariationSettings: "'SOFT' 100" };
  16. const FILTER_ID = "hero-droplet-lens";
  17. /** How much the full-size lens magnifies. */
  18. const MAGNIFY = 1.18;
  19. const clamp = (v: number, min: number, max: number) =>
  20. Math.min(max, Math.max(min, v));
  21. const letter = (ch: string, i: number) => (
  22. <span
  23. key={i}
  24. className={cn("inline-block", ch === " " && "w-[0.24em]")}
  25. data-wave={i}
  26. style={REST}
  27. >
  28. {ch === " " ? " " : ch}
  29. </span>
  30. );
  31. // Sized in CSS (.hero-title): one line, or two when the card has the height.
  32. function Title() {
  33. return (
  34. <h1
  35. aria-label={TEXT}
  36. className="hero-title font-display tracking-[-0.022em] whitespace-nowrap"
  37. >
  38. <span aria-hidden>
  39. {LEAD.split("").map((ch, i) => letter(ch, i))}
  40. <span className="hero-tail inline-block">
  41. {/* One plain text node, the one form of background-clip: text every
  42. Safari paints: split into letters, the gradient name vanished on
  43. iPhone. The wave weighs the name as a whole. */}
  44. <span className="hero-name" data-wave={LEAD.length} style={REST}>
  45. {NAME}
  46. </span>
  47. <span
  48. className="inline-block"
  49. data-period=""
  50. data-wave={TEXT.length - 1}
  51. style={REST}
  52. >
  53. .
  54. <span
  55. className="inline-block size-0 align-baseline"
  56. data-baseline
  57. />
  58. </span>
  59. </span>
  60. </span>
  61. </h1>
  62. );
  63. }
  64. /**
  65. * The headline. Letters melt under the cursor (Fraunces' weight and SOFT axes), and the
  66. * period is a bead of liquid glass: pull it and it swells into a lens that
  67. * magnifies whatever on the card it passes over, stretching with speed; let
  68. * go and it springs home and shrinks back into a period. The lens shows a
  69. * pixel-aligned copy of the card, so it works in every browser.
  70. */
  71. export function HeroTitle() {
  72. const wrapRef = useRef<HTMLDivElement>(null);
  73. const orbRef = useRef<HTMLDivElement>(null);
  74. const cloneRef = useRef<HTMLDivElement>(null);
  75. const handleRef = useRef<HTMLSpanElement>(null);
  76. const relayout = useRef<() => void>(() => {});
  77. const [map, setMap] = useState<LensMap | null>(null);
  78. /* ---------- Variable-weight wave ---------- */
  79. useEffect(() => {
  80. const wrap = wrapRef.current;
  81. if (!wrap) return;
  82. let frame = 0;
  83. /** `fx` gives each letter's closeness to the wave (0 to 1) from its box, or null for rest. */
  84. const setWeights = (fx: (box: DOMRect) => number | null) => {
  85. // The lens's copy of the card has the same letters: weigh them alike.
  86. const nodes = [...wrap.querySelectorAll<HTMLElement>("[data-wave]")];
  87. const originals = nodes.filter((el) => !el.closest("[data-clone]"));
  88. const boxes = originals.map((el) => el.getBoundingClientRect());
  89. const styles = new Map<string, [string, string]>();
  90. originals.forEach((el, i) => {
  91. const g = fx(boxes[i]);
  92. const weight = g === null ? REST.fontWeight : Math.round(500 + 400 * g);
  93. const soft =
  94. g === null
  95. ? REST.fontVariationSettings
  96. : `'SOFT' ${Math.round(20 + 80 * g)}`;
  97. styles.set(el.dataset.wave!, [String(weight), soft]);
  98. });
  99. nodes.forEach((node) => {
  100. const style = styles.get(node.dataset.wave!);
  101. if (!style) return;
  102. node.style.fontWeight = style[0];
  103. node.style.fontVariationSettings = style[1];
  104. });
  105. // Heavier letters are wider: keep the bead on the period as it moves.
  106. relayout.current();
  107. };
  108. // Closeness to a point; with no y, to a vertical line (the sweep crosses both lines at once).
  109. const near = (x: number, y?: number) => (b: DOMRect) =>
  110. Math.exp(
  111. -(
  112. (b.left + b.width / 2 - x) ** 2 +
  113. (y === undefined ? 0 : (b.top + b.height / 2 - y) ** 2)
  114. ) /
  115. (2 * 64 ** 2),
  116. );
  117. const onMove = (e: PointerEvent) => {
  118. if (e.pointerType === "touch") return;
  119. const { clientX: x, clientY: y } = e;
  120. cancelAnimationFrame(frame);
  121. frame = requestAnimationFrame(() => setWeights(near(x, y)));
  122. };
  123. const onLeave = () => {
  124. cancelAnimationFrame(frame);
  125. frame = requestAnimationFrame(() => setWeights(() => null));
  126. };
  127. // One sweep on load so touch visitors see it too.
  128. let sweepFrame = 0;
  129. let sweepTimer = 0;
  130. if (!prefersReducedMotion()) {
  131. const run = (start: number) => (now: number) => {
  132. const t = (now - start) / 1400;
  133. const r = wrap.getBoundingClientRect();
  134. if (t >= 1) {
  135. setWeights(() => null);
  136. return;
  137. }
  138. setWeights(near(r.left - 60 + (r.width + 120) * t));
  139. sweepFrame = requestAnimationFrame(run(start));
  140. };
  141. sweepTimer = window.setTimeout(() => {
  142. sweepFrame = requestAnimationFrame(run(performance.now()));
  143. }, 600);
  144. }
  145. wrap.addEventListener("pointermove", onMove);
  146. wrap.addEventListener("pointerleave", onLeave);
  147. return () => {
  148. cancelAnimationFrame(frame);
  149. cancelAnimationFrame(sweepFrame);
  150. window.clearTimeout(sweepTimer);
  151. wrap.removeEventListener("pointermove", onMove);
  152. wrap.removeEventListener("pointerleave", onLeave);
  153. };
  154. }, []);
  155. /* ---------- The glass period ---------- */
  156. useEffect(() => {
  157. const wrap = wrapRef.current;
  158. const orb = orbRef.current;
  159. const clone = cloneRef.current;
  160. const handle = handleRef.current;
  161. const card = wrap?.closest<HTMLElement>("[data-hero]");
  162. if (!wrap || !orb || !clone || !handle || !card) return;
  163. const unlight = registerLight(orb);
  164. const size = orb.offsetWidth;
  165. const half = size / 2;
  166. const still = prefersReducedMotion();
  167. // Only Chromium draws the refraction filter in place: WebKit misplaces it,
  168. // leaving a dark disc with a stray fragment. Elsewhere the copy is simply
  169. // scaled up under the lens.
  170. const refract = supportsBackdropRefraction();
  171. // Real glass is subtle: a gentle loupe in the middle, light bending hard only at the rim.
  172. if (refract) {
  173. setMap(
  174. buildLensMap({
  175. width: size,
  176. height: size,
  177. radius: half,
  178. bezel: size * 0.3,
  179. thickness: size * 0.22,
  180. magnify: MAGNIFY,
  181. }),
  182. );
  183. }
  184. // What the lens shows: a copy of the whole card, held in place under it,
  185. // so it magnifies whatever it passes over. Recopied when the card changes
  186. // size and each time the bead is picked up (the avatar may have flipped).
  187. const area = { x: 0, y: 0, w: 0, h: 0 };
  188. const copyCard = () => {
  189. clone.replaceChildren();
  190. const copy = card.cloneNode(true) as HTMLElement;
  191. copy
  192. .querySelectorAll("[data-droplet], [data-grab]")
  193. .forEach((el) => el.remove());
  194. copy.querySelectorAll("[id]").forEach((el) => el.removeAttribute("id"));
  195. copy.querySelectorAll("[data-period], [data-baseline]").forEach((el) => {
  196. el.removeAttribute("data-period");
  197. el.removeAttribute("data-baseline");
  198. });
  199. copy.removeAttribute("data-hero");
  200. copy.setAttribute("aria-hidden", "true");
  201. copy.inert = true;
  202. copy.style.width = `${card.offsetWidth}px`;
  203. copy.style.height = `${card.offsetHeight}px`;
  204. clone.append(copy);
  205. // The card's box, in the same frame as the bead's position.
  206. const c = card.getBoundingClientRect();
  207. const w = wrap.getBoundingClientRect();
  208. area.x = c.left - w.left;
  209. area.y = c.top - w.top;
  210. area.w = c.width;
  211. area.h = c.height;
  212. };
  213. // Where the period's dot is, from the font's real ink bounds.
  214. const home = { x: 0, y: 0, s: 0.16 };
  215. const measure = document.createElement("canvas").getContext("2d");
  216. const findHome = () => {
  217. const period = wrap.querySelector<HTMLElement>("[data-period]");
  218. const base = wrap.querySelector<HTMLElement>("[data-baseline]");
  219. if (!period || !base) return;
  220. const w = wrap.getBoundingClientRect();
  221. const r = period.getBoundingClientRect();
  222. const css = getComputedStyle(period);
  223. const fontSize = parseFloat(css.fontSize);
  224. let left = 0.06 * fontSize;
  225. let right = 0.2 * fontSize;
  226. let ascent = 0.15 * fontSize;
  227. if (measure) {
  228. measure.font = `${css.fontWeight} ${css.fontSize} ${css.fontFamily}`;
  229. const m = measure.measureText(".");
  230. left = -m.actualBoundingBoxLeft;
  231. right = m.actualBoundingBoxRight;
  232. ascent = m.actualBoundingBoxAscent;
  233. }
  234. // The dot is round. Some engines give the advance rather than the ink
  235. // for its width, so trust the smaller measure.
  236. const dot = Math.min(right - left, ascent);
  237. home.x = r.left - w.left + (left + right) / 2;
  238. home.y = base.getBoundingClientRect().top - w.top - ascent / 2;
  239. home.s = Math.min(0.5, (dot * 1.12) / size);
  240. handle.style.transform = `translate(${home.x}px, ${home.y}px)`;
  241. };
  242. // Center (x, y), scale s, and a jelly stretch along the direction of travel.
  243. const p = {
  244. x: 0,
  245. y: 0,
  246. vx: 0,
  247. vy: 0,
  248. s: 0.16,
  249. vs: 0,
  250. def: 0,
  251. dv: 0,
  252. angle: 0,
  253. };
  254. let held = false;
  255. let hover = false;
  256. let target = { x: 0, y: 0 };
  257. const render = () => {
  258. const a = (p.angle * 180) / Math.PI;
  259. const s = Math.max(0.05, p.s);
  260. orb.style.transform = `translate(${p.x - half}px, ${p.y - half}px) rotate(${a}deg) scale(${s * (1 + p.def)}, ${
  261. s * (1 - p.def * 0.7)
  262. }) rotate(${-a}deg)`;
  263. // Counter-scale the copy so the lens shows the card at true size and
  264. // place; without the refraction map, the copy grows as the bead does.
  265. const grow = refract
  266. ? 1
  267. : 1 + (MAGNIFY - 1) * clamp((s - home.s) / (1 - home.s), 0, 1);
  268. const k = grow / s;
  269. clone.style.transform = `translate(${half + (area.x - p.x) * k}px, ${
  270. half + (area.y - p.y) * k
  271. }px) scale(${k})`;
  272. };
  273. const settle = () => {
  274. p.x = home.x;
  275. p.y = home.y;
  276. p.s = home.s;
  277. p.vx = p.vy = p.vs = p.def = p.dv = 0;
  278. render();
  279. };
  280. copyCard();
  281. findHome();
  282. settle();
  283. orb.style.opacity = "1";
  284. // A moment after load the bead swells and settles once: a wink that it can be pulled.
  285. let wink = false;
  286. let winkTimer = 0;
  287. const winkStart = still
  288. ? 0
  289. : window.setTimeout(() => {
  290. if (held) return;
  291. wink = true;
  292. kick();
  293. winkTimer = window.setTimeout(() => {
  294. wink = false;
  295. kick();
  296. }, 700);
  297. }, 2600);
  298. let frame = 0;
  299. let last = performance.now();
  300. let lift = 0;
  301. const step = (now: number) => {
  302. const dt = Math.min(32, now - last) / 16.67;
  303. const goal = held ? target : home;
  304. // Hovering swells the bead a little: an invitation to pull it.
  305. const goalS = held ? 1 : hover || wink ? home.s * 1.55 : home.s;
  306. last = now;
  307. if (held) {
  308. // Follow the finger closely, with a little lag that reads as weight.
  309. const nx = p.x + (goal.x - p.x) * Math.min(1, 0.45 * dt);
  310. const ny = p.y + (goal.y - p.y) * Math.min(1, 0.45 * dt);
  311. p.vx = 0.7 * p.vx + 0.3 * ((nx - p.x) / dt);
  312. p.vy = 0.7 * p.vy + 0.3 * ((ny - p.y) / dt);
  313. p.x = nx;
  314. p.y = ny;
  315. } else {
  316. // An underdamped spring home, so it overshoots a touch and settles.
  317. p.vx += ((goal.x - p.x) * 0.075 - p.vx * 0.3) * dt;
  318. p.vy += ((goal.y - p.y) * 0.075 - p.vy * 0.3) * dt;
  319. p.x += p.vx * dt;
  320. p.y += p.vy * dt;
  321. }
  322. p.vs += ((goalS - p.s) * 0.12 - p.vs * 0.5) * dt;
  323. p.s += p.vs * dt;
  324. const speed = Math.hypot(p.vx, p.vy);
  325. if (speed > 0.4) p.angle = Math.atan2(p.vy, p.vx);
  326. const stretch = Math.min(0.28, speed * 0.016);
  327. p.dv += (stretch - p.def) * 0.16 * dt;
  328. p.dv *= Math.pow(0.8, dt);
  329. p.def += p.dv * dt;
  330. render();
  331. const moving =
  332. held ||
  333. speed > 0.03 ||
  334. Math.abs(goal.x - p.x) > 0.1 ||
  335. Math.abs(goal.y - p.y) > 0.1 ||
  336. Math.abs(goalS - p.s) > 0.002 ||
  337. Math.abs(p.vs) > 0.001 ||
  338. Math.abs(p.dv) > 0.0005;
  339. if (moving) {
  340. frame = requestAnimationFrame(step);
  341. } else {
  342. frame = 0;
  343. if (!hover && !wink) settle();
  344. }
  345. };
  346. const kick = () => {
  347. if (still) {
  348. if (held) {
  349. p.x = target.x;
  350. p.y = target.y;
  351. p.s = 1;
  352. render();
  353. } else settle();
  354. return;
  355. }
  356. if (!frame) {
  357. last = performance.now();
  358. frame = requestAnimationFrame(step);
  359. }
  360. };
  361. const aim = (e: PointerEvent) => {
  362. const w = wrap.getBoundingClientRect();
  363. // On touch, float the lens above the finger like iOS's loupe. It stays
  364. // on the card, where its copy has something to show.
  365. target = {
  366. x: clamp(e.clientX - w.left, area.x + half, area.x + area.w - half),
  367. y: clamp(
  368. e.clientY - w.top - lift,
  369. area.y + half,
  370. area.y + area.h - half,
  371. ),
  372. };
  373. };
  374. const onDown = (e: PointerEvent) => {
  375. e.preventDefault();
  376. handle.setPointerCapture(e.pointerId);
  377. copyCard();
  378. held = true;
  379. lift = e.pointerType === "touch" ? size * 0.85 : 0;
  380. aim(e);
  381. kick();
  382. };
  383. const onMove = (e: PointerEvent) => {
  384. if (!held) return;
  385. aim(e);
  386. kick();
  387. };
  388. // Let go: the spring home starts from the lens's current velocity.
  389. const onUp = () => {
  390. if (!held) return;
  391. held = false;
  392. kick();
  393. };
  394. const onEnter = (e: PointerEvent) => {
  395. if (e.pointerType === "touch") return;
  396. hover = true;
  397. kick();
  398. };
  399. const onLeave = () => {
  400. hover = false;
  401. kick();
  402. };
  403. relayout.current = () => {
  404. findHome();
  405. if (held || frame) return;
  406. p.x = home.x;
  407. p.y = home.y;
  408. if (!hover) p.s = home.s;
  409. render();
  410. };
  411. const onResize = () => relayout.current();
  412. const ro = new ResizeObserver(() => {
  413. copyCard();
  414. relayout.current();
  415. });
  416. handle.addEventListener("pointerdown", onDown);
  417. handle.addEventListener("pointermove", onMove);
  418. handle.addEventListener("pointerup", onUp);
  419. handle.addEventListener("pointercancel", onUp);
  420. handle.addEventListener("pointerenter", onEnter);
  421. handle.addEventListener("pointerleave", onLeave);
  422. window.addEventListener("resize", onResize);
  423. ro.observe(card);
  424. document.fonts.ready.then(() => {
  425. copyCard();
  426. relayout.current();
  427. });
  428. return () => {
  429. cancelAnimationFrame(frame);
  430. window.clearTimeout(winkStart);
  431. window.clearTimeout(winkTimer);
  432. unlight();
  433. relayout.current = () => {};
  434. handle.removeEventListener("pointerdown", onDown);
  435. handle.removeEventListener("pointermove", onMove);
  436. handle.removeEventListener("pointerup", onUp);
  437. handle.removeEventListener("pointercancel", onUp);
  438. handle.removeEventListener("pointerenter", onEnter);
  439. handle.removeEventListener("pointerleave", onLeave);
  440. window.removeEventListener("resize", onResize);
  441. ro.disconnect();
  442. };
  443. }, []);
  444. return (
  445. <div ref={wrapRef} className="relative -mx-1 px-1 py-1">
  446. <Title />
  447. <div
  448. ref={orbRef}
  449. aria-hidden
  450. data-droplet
  451. className="lg pointer-events-none absolute top-0 left-0 z-10 size-[76px] rounded-full opacity-0 shadow-[0_14px_28px_-14px_rgb(0_0_0/0.4),0_2px_6px_-2px_rgb(0_0_0/0.18)] transition-opacity duration-700 [--lg-blur:0px] [backdrop-filter:none] [background:transparent] sm:size-[96px]"
  452. >
  453. {map && (
  454. <GlassFilter
  455. blur={0.2}
  456. chroma={0.025}
  457. id={FILTER_ID}
  458. map={map}
  459. saturate={1.05}
  460. />
  461. )}
  462. <div
  463. className="absolute inset-0 overflow-hidden rounded-full bg-[#eff4fa] [clip-path:circle(50%)] dark:bg-[#18212b]"
  464. style={{ filter: map ? `url(#${FILTER_ID})` : undefined }}
  465. >
  466. {/* Filled with a copy of the card from the effect; React keeps it empty. */}
  467. <div
  468. ref={cloneRef}
  469. className="absolute top-0 left-0 origin-top-left"
  470. data-clone
  471. />
  472. </div>
  473. {/* Bubble shading: rim thickness, a glossy specular highlight, and a soft caustic. */}
  474. <span className="pointer-events-none absolute inset-0 rounded-full shadow-[inset_0_0_0_1px_rgb(255_255_255/0.35),inset_0_12px_18px_-12px_rgb(255_255_255/0.75),inset_0_-14px_22px_-14px_rgb(255_255_255/0.5),inset_0_0_10px_rgb(0_0_0/0.05)]" />
  475. <span className="pointer-events-none absolute top-[9%] left-[19%] h-[22%] w-[44%] -rotate-[22deg] rounded-[50%] bg-[radial-gradient(closest-side,rgb(255_255_255/0.9),rgb(255_255_255/0))] opacity-75 mix-blend-screen" />
  476. <span className="pointer-events-none absolute right-[17%] bottom-[11%] h-[11%] w-[24%] -rotate-[22deg] rounded-[50%] bg-[radial-gradient(closest-side,rgb(255_255_255/0.55),transparent)] opacity-60" />
  477. </div>
  478. {/* A generous grab target around the period (the bead itself is tiny). */}
  479. <span
  480. ref={handleRef}
  481. aria-hidden
  482. className="absolute top-0 left-0 z-20 -mt-6 -ml-6 size-12 cursor-grab touch-none rounded-full active:cursor-grabbing"
  483. data-cursor="Pull the period"
  484. data-grab
  485. data-nodrag
  486. />
  487. </div>
  488. );
  489. }