hero-title.tsx 20 KB

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