hero-title.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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. // Pulling the bead captures the pointer, so moves keep arriving once it
  121. // has left the headline: out there the letters rest, as on leaving.
  122. const r = wrap.getBoundingClientRect();
  123. const inside = x >= r.left && x <= r.right && y >= r.top && y <= r.bottom;
  124. cancelAnimationFrame(frame);
  125. frame = requestAnimationFrame(() =>
  126. setWeights(inside ? near(x, y) : () => null),
  127. );
  128. };
  129. const onLeave = () => {
  130. cancelAnimationFrame(frame);
  131. frame = requestAnimationFrame(() => setWeights(() => null));
  132. };
  133. // One sweep on load so touch visitors see it too.
  134. let sweepFrame = 0;
  135. let sweepTimer = 0;
  136. if (!prefersReducedMotion()) {
  137. const run = (start: number) => (now: number) => {
  138. const t = (now - start) / 1400;
  139. const r = wrap.getBoundingClientRect();
  140. if (t >= 1) {
  141. setWeights(() => null);
  142. return;
  143. }
  144. setWeights(near(r.left - 60 + (r.width + 120) * t));
  145. sweepFrame = requestAnimationFrame(run(start));
  146. };
  147. sweepTimer = window.setTimeout(() => {
  148. sweepFrame = requestAnimationFrame(run(performance.now()));
  149. }, 600);
  150. }
  151. wrap.addEventListener("pointermove", onMove);
  152. wrap.addEventListener("pointerleave", onLeave);
  153. return () => {
  154. cancelAnimationFrame(frame);
  155. cancelAnimationFrame(sweepFrame);
  156. window.clearTimeout(sweepTimer);
  157. wrap.removeEventListener("pointermove", onMove);
  158. wrap.removeEventListener("pointerleave", onLeave);
  159. };
  160. }, []);
  161. /* ---------- The glass period ---------- */
  162. useEffect(() => {
  163. const wrap = wrapRef.current;
  164. const orb = orbRef.current;
  165. const clone = cloneRef.current;
  166. const handle = handleRef.current;
  167. const card = wrap?.closest<HTMLElement>("[data-hero]");
  168. if (!wrap || !orb || !clone || !handle || !card) return;
  169. const unlight = registerLight(orb);
  170. const size = orb.offsetWidth;
  171. const half = size / 2;
  172. const still = prefersReducedMotion();
  173. // Only Chromium draws the refraction filter in place: WebKit misplaces it,
  174. // leaving a dark disc with a stray fragment. Elsewhere the copy is simply
  175. // scaled up under the lens.
  176. const refract = supportsBackdropRefraction();
  177. // Ancestors may be scaled (a pressed card), so rects are turned back into
  178. // the wrapper's own pixels before they place anything.
  179. const scaleOf = (w: DOMRect) => w.width / wrap.offsetWidth || 1;
  180. // Real glass is subtle: a gentle loupe in the middle, light bending hard only at the rim.
  181. if (refract) {
  182. setMap(
  183. buildLensMap({
  184. width: size,
  185. height: size,
  186. radius: half,
  187. bezel: size * 0.3,
  188. thickness: size * 0.22,
  189. magnify: MAGNIFY,
  190. }),
  191. );
  192. }
  193. // What the lens shows: a copy of the whole card, held in place under it,
  194. // so it magnifies whatever it passes over. Recopied when the card changes
  195. // size and each time the bead is picked up (the avatar may have flipped).
  196. const area = { x: 0, y: 0, w: 0, h: 0 };
  197. const copyCard = () => {
  198. // Hidden by a view (phones hide the hero for Work): keep the copy we have.
  199. if (!card.offsetWidth) return;
  200. clone.replaceChildren();
  201. const copy = card.cloneNode(true) as HTMLElement;
  202. copy
  203. .querySelectorAll("[data-droplet], [data-grab]")
  204. .forEach((el) => el.remove());
  205. copy.querySelectorAll("[id]").forEach((el) => el.removeAttribute("id"));
  206. copy.querySelectorAll("[data-period], [data-baseline]").forEach((el) => {
  207. el.removeAttribute("data-period");
  208. el.removeAttribute("data-baseline");
  209. });
  210. copy.removeAttribute("data-hero");
  211. copy.setAttribute("aria-hidden", "true");
  212. copy.inert = true;
  213. copy.style.width = `${card.offsetWidth}px`;
  214. copy.style.height = `${card.offsetHeight}px`;
  215. clone.append(copy);
  216. // The card's box, in the same frame as the bead's position.
  217. const c = card.getBoundingClientRect();
  218. const w = wrap.getBoundingClientRect();
  219. const k = scaleOf(w);
  220. area.x = (c.left - w.left) / k;
  221. area.y = (c.top - w.top) / k;
  222. area.w = c.width / k;
  223. area.h = c.height / k;
  224. };
  225. // Where the period's dot is, from the font's real ink bounds.
  226. const home = { x: 0, y: 0, s: 0.16 };
  227. const measure = document.createElement("canvas").getContext("2d");
  228. const findHome = () => {
  229. const period = wrap.querySelector<HTMLElement>("[data-period]");
  230. const base = wrap.querySelector<HTMLElement>("[data-baseline]");
  231. // Hidden, there's nothing to measure: keep the last home.
  232. if (!period || !base || !wrap.offsetWidth) return;
  233. const w = wrap.getBoundingClientRect();
  234. const k = scaleOf(w);
  235. const r = period.getBoundingClientRect();
  236. const css = getComputedStyle(period);
  237. const fontSize = parseFloat(css.fontSize);
  238. let left = 0.06 * fontSize;
  239. let right = 0.2 * fontSize;
  240. let ascent = 0.15 * fontSize;
  241. if (measure) {
  242. measure.font = `${css.fontWeight} ${css.fontSize} ${css.fontFamily}`;
  243. const m = measure.measureText(".");
  244. left = -m.actualBoundingBoxLeft;
  245. right = m.actualBoundingBoxRight;
  246. ascent = m.actualBoundingBoxAscent;
  247. }
  248. // The dot is round. Some engines give the advance rather than the ink
  249. // for its width, so trust the smaller measure.
  250. const dot = Math.min(right - left, ascent);
  251. home.x = (r.left - w.left) / k + (left + right) / 2;
  252. home.y = (base.getBoundingClientRect().top - w.top) / k - ascent / 2;
  253. home.s = Math.min(0.5, (dot * 1.12) / size);
  254. handle.style.transform = `translate(${home.x}px, ${home.y}px)`;
  255. };
  256. // Center (x, y), scale s, and a jelly stretch along the direction of travel.
  257. const p = {
  258. x: 0,
  259. y: 0,
  260. vx: 0,
  261. vy: 0,
  262. s: 0.16,
  263. vs: 0,
  264. def: 0,
  265. dv: 0,
  266. angle: 0,
  267. };
  268. let held = false;
  269. let hover = false;
  270. let target = { x: 0, y: 0 };
  271. const render = () => {
  272. const a = (p.angle * 180) / Math.PI;
  273. const s = Math.max(0.05, p.s);
  274. orb.style.transform = `translate(${p.x - half}px, ${p.y - half}px) rotate(${a}deg) scale(${s * (1 + p.def)}, ${
  275. s * (1 - p.def * 0.7)
  276. }) rotate(${-a}deg)`;
  277. // Counter-scale the copy so the lens shows the card at true size and
  278. // place; without the refraction map, the copy grows as the bead does.
  279. const grow = refract
  280. ? 1
  281. : 1 + (MAGNIFY - 1) * clamp((s - home.s) / (1 - home.s), 0, 1);
  282. const k = grow / s;
  283. clone.style.transform = `translate(${half + (area.x - p.x) * k}px, ${
  284. half + (area.y - p.y) * k
  285. }px) scale(${k})`;
  286. };
  287. const settle = () => {
  288. p.x = home.x;
  289. p.y = home.y;
  290. p.s = home.s;
  291. p.vx = p.vy = p.vs = p.def = p.dv = 0;
  292. render();
  293. };
  294. copyCard();
  295. findHome();
  296. settle();
  297. orb.style.opacity = "1";
  298. // A moment after load the bead swells and settles once: a wink that it can be pulled.
  299. let wink = false;
  300. let winkTimer = 0;
  301. const winkStart = still
  302. ? 0
  303. : window.setTimeout(() => {
  304. if (held) return;
  305. wink = true;
  306. kick();
  307. winkTimer = window.setTimeout(() => {
  308. wink = false;
  309. kick();
  310. }, 700);
  311. }, 2600);
  312. let frame = 0;
  313. let last = performance.now();
  314. let lift = 0;
  315. const step = (now: number) => {
  316. const dt = Math.min(32, now - last) / 16.67;
  317. const goal = held ? target : home;
  318. // Hovering swells the bead a little: an invitation to pull it.
  319. const goalS = held ? 1 : hover || wink ? home.s * 1.55 : home.s;
  320. last = now;
  321. if (held) {
  322. // Follow the finger closely, with a little lag that reads as weight.
  323. const nx = p.x + (goal.x - p.x) * Math.min(1, 0.45 * dt);
  324. const ny = p.y + (goal.y - p.y) * Math.min(1, 0.45 * dt);
  325. p.vx = 0.7 * p.vx + 0.3 * ((nx - p.x) / dt);
  326. p.vy = 0.7 * p.vy + 0.3 * ((ny - p.y) / dt);
  327. p.x = nx;
  328. p.y = ny;
  329. } else {
  330. // An underdamped spring home, so it overshoots a touch and settles.
  331. p.vx += ((goal.x - p.x) * 0.075 - p.vx * 0.3) * dt;
  332. p.vy += ((goal.y - p.y) * 0.075 - p.vy * 0.3) * dt;
  333. p.x += p.vx * dt;
  334. p.y += p.vy * dt;
  335. }
  336. p.vs += ((goalS - p.s) * 0.12 - p.vs * 0.5) * dt;
  337. p.s += p.vs * dt;
  338. const speed = Math.hypot(p.vx, p.vy);
  339. if (speed > 0.4) p.angle = Math.atan2(p.vy, p.vx);
  340. const stretch = Math.min(0.28, speed * 0.016);
  341. p.dv += (stretch - p.def) * 0.16 * dt;
  342. p.dv *= Math.pow(0.8, dt);
  343. p.def += p.dv * dt;
  344. render();
  345. const moving =
  346. held ||
  347. speed > 0.03 ||
  348. Math.abs(goal.x - p.x) > 0.1 ||
  349. Math.abs(goal.y - p.y) > 0.1 ||
  350. Math.abs(goalS - p.s) > 0.002 ||
  351. Math.abs(p.vs) > 0.001 ||
  352. Math.abs(p.dv) > 0.0005;
  353. if (moving) {
  354. frame = requestAnimationFrame(step);
  355. } else {
  356. frame = 0;
  357. if (!hover && !wink) settle();
  358. }
  359. };
  360. const kick = () => {
  361. if (still) {
  362. if (held) {
  363. p.x = target.x;
  364. p.y = target.y;
  365. p.s = 1;
  366. render();
  367. } else settle();
  368. return;
  369. }
  370. if (!frame) {
  371. last = performance.now();
  372. frame = requestAnimationFrame(step);
  373. }
  374. };
  375. const aim = (e: PointerEvent) => {
  376. const w = wrap.getBoundingClientRect();
  377. const k = scaleOf(w);
  378. // On touch, float the lens above the finger like iOS's loupe. It stays
  379. // on the card, where its copy has something to show.
  380. target = {
  381. x: clamp(
  382. (e.clientX - w.left) / k,
  383. area.x + half,
  384. area.x + area.w - half,
  385. ),
  386. y: clamp(
  387. (e.clientY - w.top) / k - lift,
  388. area.y + half,
  389. area.y + area.h - half,
  390. ),
  391. };
  392. };
  393. const onDown = (e: PointerEvent) => {
  394. e.preventDefault();
  395. handle.setPointerCapture(e.pointerId);
  396. // The press is cancelled, so it no longer clears a selection by itself.
  397. getSelection()?.removeAllRanges();
  398. copyCard();
  399. held = true;
  400. lift = e.pointerType === "touch" ? size * 0.85 : 0;
  401. aim(e);
  402. kick();
  403. };
  404. const onMove = (e: PointerEvent) => {
  405. if (!held) return;
  406. aim(e);
  407. kick();
  408. };
  409. // Let go: the spring home starts from the lens's current velocity.
  410. const onUp = () => {
  411. if (!held) return;
  412. held = false;
  413. kick();
  414. };
  415. const onEnter = (e: PointerEvent) => {
  416. if (e.pointerType === "touch") return;
  417. hover = true;
  418. kick();
  419. };
  420. const onLeave = () => {
  421. hover = false;
  422. kick();
  423. };
  424. // iOS turns a long press into a text selection (loupe and handles
  425. // included) whatever touch-action says, and the pull then drags it across
  426. // the card. A handled touchstart keeps the press the bead's.
  427. const onTouchStart = (e: TouchEvent) => e.preventDefault();
  428. const onSelectStart = (e: Event) => {
  429. if (held) e.preventDefault();
  430. };
  431. relayout.current = () => {
  432. findHome();
  433. if (held || frame) return;
  434. p.x = home.x;
  435. p.y = home.y;
  436. if (!hover) p.s = home.s;
  437. render();
  438. };
  439. const onResize = () => relayout.current();
  440. // Resized, or shown again after a view hid it: the bead goes straight
  441. // home rather than springing there from wherever it was last measured.
  442. const ro = new ResizeObserver(() => {
  443. if (!card.offsetWidth) return;
  444. copyCard();
  445. findHome();
  446. if (held) return;
  447. cancelAnimationFrame(frame);
  448. frame = 0;
  449. settle();
  450. });
  451. handle.addEventListener("pointerdown", onDown);
  452. handle.addEventListener("pointermove", onMove);
  453. handle.addEventListener("pointerup", onUp);
  454. handle.addEventListener("pointercancel", onUp);
  455. handle.addEventListener("pointerenter", onEnter);
  456. handle.addEventListener("pointerleave", onLeave);
  457. handle.addEventListener("touchstart", onTouchStart, { passive: false });
  458. document.addEventListener("selectstart", onSelectStart);
  459. window.addEventListener("resize", onResize);
  460. ro.observe(card);
  461. document.fonts.ready.then(() => {
  462. copyCard();
  463. relayout.current();
  464. });
  465. // On a first visit the web fonts land late (html.ff) and move the period.
  466. const html = document.documentElement;
  467. let fonts = html.classList.contains("ff");
  468. const mo = new MutationObserver(() => {
  469. if (html.classList.contains("ff") === fonts) return;
  470. fonts = !fonts;
  471. copyCard();
  472. relayout.current();
  473. });
  474. mo.observe(html, { attributes: true, attributeFilter: ["class"] });
  475. return () => {
  476. cancelAnimationFrame(frame);
  477. window.clearTimeout(winkStart);
  478. window.clearTimeout(winkTimer);
  479. unlight();
  480. relayout.current = () => {};
  481. handle.removeEventListener("pointerdown", onDown);
  482. handle.removeEventListener("pointermove", onMove);
  483. handle.removeEventListener("pointerup", onUp);
  484. handle.removeEventListener("pointercancel", onUp);
  485. handle.removeEventListener("pointerenter", onEnter);
  486. handle.removeEventListener("pointerleave", onLeave);
  487. handle.removeEventListener("touchstart", onTouchStart);
  488. document.removeEventListener("selectstart", onSelectStart);
  489. window.removeEventListener("resize", onResize);
  490. ro.disconnect();
  491. mo.disconnect();
  492. };
  493. }, []);
  494. return (
  495. <div ref={wrapRef} className="relative -mx-1 px-1 py-1">
  496. <Title />
  497. <div
  498. ref={orbRef}
  499. aria-hidden
  500. data-droplet
  501. className="lg pointer-events-none absolute top-0 left-0 z-10 size-[76px] rounded-full opacity-0 select-none 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]"
  502. >
  503. {map && (
  504. <GlassFilter
  505. blur={0.2}
  506. chroma={0.025}
  507. id={FILTER_ID}
  508. map={map}
  509. saturate={1.05}
  510. />
  511. )}
  512. <div
  513. className="absolute inset-0 overflow-hidden rounded-full bg-[#eff4fa] [clip-path:circle(50%)] dark:bg-[#18212b]"
  514. style={{ filter: map ? `url(#${FILTER_ID})` : undefined }}
  515. >
  516. {/* Filled with a copy of the card from the effect; React keeps it empty. */}
  517. <div
  518. ref={cloneRef}
  519. className="absolute top-0 left-0 origin-top-left"
  520. data-clone
  521. />
  522. </div>
  523. {/* Bubble shading: rim thickness, a glossy specular highlight, and a soft caustic. */}
  524. <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)]" />
  525. <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" />
  526. <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" />
  527. </div>
  528. {/* A generous grab target around the period (the bead itself is tiny). */}
  529. <span
  530. ref={handleRef}
  531. aria-hidden
  532. className="absolute top-0 left-0 z-20 -mt-6 -ml-6 size-12 cursor-grab touch-none rounded-full select-none active:cursor-grabbing"
  533. data-cursor="Pull the period"
  534. data-grab
  535. data-nodrag
  536. />
  537. </div>
  538. );
  539. }