hero-title.tsx 20 KB

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