hero-title.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. "use client";
  2. import { useEffect, useRef, useState } from "react";
  3. import { buildLensMap, type LensMap } from "@/components/glass/displacement";
  4. import { GlassFilter, registerLight } from "@/components/glass/liquid-glass";
  5. import { cn, prefersReducedMotion } from "@/lib/utils";
  6. const LEAD = "Hey, I'm ";
  7. const NAME = "Eric";
  8. const TEXT = `${LEAD}${NAME}.`;
  9. const BASE_WEIGHT = 640;
  10. /** At rest the letters are fully soft; the wave sharpens what it passes and melts what it touches. */
  11. const REST = { fontWeight: BASE_WEIGHT, fontVariationSettings: "'SOFT' 100" };
  12. const FILTER_ID = "hero-droplet-lens";
  13. /** Matches the wrapper's px-1/py-1, so the clone inside the lens lines up with the title. */
  14. const PAD = 4;
  15. const letter = (ch: string, i: number) => (
  16. <span
  17. key={i}
  18. className={cn("inline-block", ch === " " && "w-[0.24em]")}
  19. data-wave={i}
  20. style={REST}
  21. >
  22. {ch === " " ? " " : ch}
  23. </span>
  24. );
  25. // From small tablets up the line scales with its card (it runs ~6.4em wide).
  26. function Title({ clone }: { clone?: boolean }) {
  27. return (
  28. <h1
  29. aria-hidden={clone || undefined}
  30. aria-label={clone ? undefined : TEXT}
  31. className="font-display text-[2.8rem] leading-[1.02] tracking-[-0.022em] whitespace-nowrap sm:text-[length:clamp(2.4rem,15.5cqi_+_2px,5.2rem)]"
  32. >
  33. <span aria-hidden>
  34. {LEAD.split("").map(letter)}
  35. <span className="hero-name">
  36. {NAME.split("").map((ch, j) => letter(ch, LEAD.length + j))}
  37. </span>
  38. <span
  39. className="inline-block"
  40. data-period={clone ? undefined : ""}
  41. data-wave={TEXT.length - 1}
  42. style={REST}
  43. >
  44. .
  45. {!clone && (
  46. <span
  47. className="inline-block size-0 align-baseline"
  48. data-baseline
  49. />
  50. )}
  51. </span>
  52. </span>
  53. </h1>
  54. );
  55. }
  56. /**
  57. * The headline. Letters melt under the cursor (Fraunces' weight and SOFT axes), and the
  58. * period is a bead of liquid glass: pull it and it swells into a lens that
  59. * magnifies whatever it passes over, stretching with speed; let go and it
  60. * springs home and shrinks back into a period. The lens refracts a
  61. * pixel-aligned copy of the title, so it works in every browser.
  62. */
  63. export function HeroTitle() {
  64. const wrapRef = useRef<HTMLDivElement>(null);
  65. const orbRef = useRef<HTMLDivElement>(null);
  66. const cloneRef = useRef<HTMLDivElement>(null);
  67. const handleRef = useRef<HTMLSpanElement>(null);
  68. const relayout = useRef<() => void>(() => {});
  69. const [map, setMap] = useState<LensMap | null>(null);
  70. const [pulled, setPulled] = useState(false);
  71. /* ---------- Variable-weight wave ---------- */
  72. useEffect(() => {
  73. const wrap = wrapRef.current;
  74. if (!wrap) return;
  75. const groups = new Map<string, HTMLElement[]>();
  76. wrap.querySelectorAll<HTMLElement>("[data-wave]").forEach((el) => {
  77. const key = el.dataset.wave!;
  78. groups.set(key, [...(groups.get(key) ?? []), el]);
  79. });
  80. const originals = [
  81. ...wrap.querySelectorAll<HTMLElement>("[data-wave]"),
  82. ].filter((el) => !el.closest("[data-clone]"));
  83. let frame = 0;
  84. /** `fx` gives each letter's closeness to the wave (0 to 1), or null for rest. */
  85. const setWeights = (fx: (center: number) => number | null) => {
  86. const centers = originals.map((el) => {
  87. const r = el.getBoundingClientRect();
  88. return r.left + r.width / 2;
  89. });
  90. originals.forEach((el, i) => {
  91. const g = fx(centers[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. groups.get(el.dataset.wave!)?.forEach((node) => {
  98. node.style.fontWeight = String(weight);
  99. node.style.fontVariationSettings = soft;
  100. });
  101. });
  102. // Heavier letters are wider: keep the bead on the period as it moves.
  103. relayout.current();
  104. };
  105. const near = (x: number) => (c: number) =>
  106. Math.exp(-((c - x) ** 2) / (2 * 64 ** 2));
  107. const onMove = (e: PointerEvent) => {
  108. if (e.pointerType === "touch") return;
  109. const x = e.clientX;
  110. cancelAnimationFrame(frame);
  111. frame = requestAnimationFrame(() => setWeights(near(x)));
  112. };
  113. const onLeave = () => {
  114. cancelAnimationFrame(frame);
  115. frame = requestAnimationFrame(() => setWeights(() => null));
  116. };
  117. // One sweep on load so touch visitors see it too.
  118. let sweepFrame = 0;
  119. let sweepTimer = 0;
  120. if (!prefersReducedMotion()) {
  121. const run = (start: number) => (now: number) => {
  122. const t = (now - start) / 1400;
  123. const r = wrap.getBoundingClientRect();
  124. if (t >= 1) {
  125. setWeights(() => null);
  126. return;
  127. }
  128. setWeights(near(r.left - 60 + (r.width + 120) * t));
  129. sweepFrame = requestAnimationFrame(run(start));
  130. };
  131. sweepTimer = window.setTimeout(() => {
  132. sweepFrame = requestAnimationFrame(run(performance.now()));
  133. }, 600);
  134. }
  135. wrap.addEventListener("pointermove", onMove);
  136. wrap.addEventListener("pointerleave", onLeave);
  137. return () => {
  138. cancelAnimationFrame(frame);
  139. cancelAnimationFrame(sweepFrame);
  140. window.clearTimeout(sweepTimer);
  141. wrap.removeEventListener("pointermove", onMove);
  142. wrap.removeEventListener("pointerleave", onLeave);
  143. };
  144. }, []);
  145. /* ---------- The glass period ---------- */
  146. useEffect(() => {
  147. const wrap = wrapRef.current;
  148. const orb = orbRef.current;
  149. const clone = cloneRef.current;
  150. const handle = handleRef.current;
  151. if (!wrap || !orb || !clone || !handle) return;
  152. const unlight = registerLight(orb);
  153. const size = orb.offsetWidth;
  154. const half = size / 2;
  155. const still = prefersReducedMotion();
  156. // Real glass is subtle: a gentle loupe in the middle, light bending hard only at the rim.
  157. setMap(
  158. buildLensMap({
  159. width: size,
  160. height: size,
  161. radius: half,
  162. bezel: size * 0.3,
  163. thickness: size * 0.22,
  164. magnify: 1.18,
  165. }),
  166. );
  167. // Where the period's dot is, from the font's real ink bounds.
  168. const home = { x: 0, y: 0, s: 0.16 };
  169. const measure = document.createElement("canvas").getContext("2d");
  170. const findHome = () => {
  171. const period = wrap.querySelector<HTMLElement>("[data-period]");
  172. const base = wrap.querySelector<HTMLElement>("[data-baseline]");
  173. if (!period || !base) return;
  174. const w = wrap.getBoundingClientRect();
  175. const r = period.getBoundingClientRect();
  176. const css = getComputedStyle(period);
  177. const fontSize = parseFloat(css.fontSize);
  178. let left = 0.06 * fontSize;
  179. let right = 0.2 * fontSize;
  180. let ascent = 0.15 * fontSize;
  181. if (measure) {
  182. measure.font = `${css.fontWeight} ${css.fontSize} ${css.fontFamily}`;
  183. const m = measure.measureText(".");
  184. left = -m.actualBoundingBoxLeft;
  185. right = m.actualBoundingBoxRight;
  186. ascent = m.actualBoundingBoxAscent;
  187. }
  188. const dot = Math.max(right - left, ascent);
  189. home.x = r.left - w.left + (left + right) / 2;
  190. home.y = base.getBoundingClientRect().top - w.top - ascent / 2;
  191. home.s = Math.min(0.5, (dot * 1.12) / size);
  192. handle.style.transform = `translate(${home.x}px, ${home.y}px)`;
  193. };
  194. // Center (x, y), scale s, and a jelly stretch along the direction of travel.
  195. const p = {
  196. x: 0,
  197. y: 0,
  198. vx: 0,
  199. vy: 0,
  200. s: 0.16,
  201. vs: 0,
  202. def: 0,
  203. dv: 0,
  204. angle: 0,
  205. };
  206. let held = false;
  207. let hover = false;
  208. let target = { x: 0, y: 0 };
  209. const render = () => {
  210. const a = (p.angle * 180) / Math.PI;
  211. const s = Math.max(0.05, p.s);
  212. orb.style.transform = `translate(${p.x - half}px, ${p.y - half}px) rotate(${a}deg) scale(${s * (1 + p.def)}, ${
  213. s * (1 - p.def * 0.7)
  214. }) rotate(${-a}deg)`;
  215. // Counter-scale the copy inside so the lens always shows the title at true size and place.
  216. const tx = (PAD - p.x) / s - PAD + half;
  217. const ty = (PAD - p.y) / s - PAD + half;
  218. clone.style.transform = `translate(${tx}px, ${ty}px) scale(${1 / s})`;
  219. };
  220. const settle = () => {
  221. p.x = home.x;
  222. p.y = home.y;
  223. p.s = home.s;
  224. p.vx = p.vy = p.vs = p.def = p.dv = 0;
  225. render();
  226. };
  227. findHome();
  228. settle();
  229. orb.style.opacity = "1";
  230. let frame = 0;
  231. let last = performance.now();
  232. let lift = 0;
  233. const step = (now: number) => {
  234. const dt = Math.min(32, now - last) / 16.67;
  235. const goal = held ? target : home;
  236. // Hovering swells the bead a little: an invitation to pull it.
  237. const goalS = held ? 1 : hover ? home.s * 1.55 : home.s;
  238. last = now;
  239. if (held) {
  240. // Follow the finger closely, with a little lag that reads as weight.
  241. const nx = p.x + (goal.x - p.x) * Math.min(1, 0.45 * dt);
  242. const ny = p.y + (goal.y - p.y) * Math.min(1, 0.45 * dt);
  243. p.vx = 0.7 * p.vx + 0.3 * ((nx - p.x) / dt);
  244. p.vy = 0.7 * p.vy + 0.3 * ((ny - p.y) / dt);
  245. p.x = nx;
  246. p.y = ny;
  247. } else {
  248. // An underdamped spring home, so it overshoots a touch and settles.
  249. p.vx += ((goal.x - p.x) * 0.075 - p.vx * 0.3) * dt;
  250. p.vy += ((goal.y - p.y) * 0.075 - p.vy * 0.3) * dt;
  251. p.x += p.vx * dt;
  252. p.y += p.vy * dt;
  253. }
  254. p.vs += ((goalS - p.s) * 0.12 - p.vs * 0.5) * dt;
  255. p.s += p.vs * dt;
  256. const speed = Math.hypot(p.vx, p.vy);
  257. if (speed > 0.4) p.angle = Math.atan2(p.vy, p.vx);
  258. const stretch = Math.min(0.28, speed * 0.016);
  259. p.dv += (stretch - p.def) * 0.16 * dt;
  260. p.dv *= Math.pow(0.8, dt);
  261. p.def += p.dv * dt;
  262. render();
  263. const moving =
  264. held ||
  265. speed > 0.03 ||
  266. Math.abs(goal.x - p.x) > 0.1 ||
  267. Math.abs(goal.y - p.y) > 0.1 ||
  268. Math.abs(goalS - p.s) > 0.002 ||
  269. Math.abs(p.vs) > 0.001 ||
  270. Math.abs(p.dv) > 0.0005;
  271. if (moving) {
  272. frame = requestAnimationFrame(step);
  273. } else {
  274. frame = 0;
  275. if (!hover) settle();
  276. }
  277. };
  278. const kick = () => {
  279. if (still) {
  280. if (held) {
  281. p.x = target.x;
  282. p.y = target.y;
  283. p.s = 1;
  284. render();
  285. } else settle();
  286. return;
  287. }
  288. if (!frame) {
  289. last = performance.now();
  290. frame = requestAnimationFrame(step);
  291. }
  292. };
  293. const aim = (e: PointerEvent) => {
  294. const w = wrap.getBoundingClientRect();
  295. // On touch, float the lens above the finger like iOS's loupe.
  296. target = { x: e.clientX - w.left, y: e.clientY - w.top - lift };
  297. };
  298. const onDown = (e: PointerEvent) => {
  299. e.preventDefault();
  300. handle.setPointerCapture(e.pointerId);
  301. held = true;
  302. lift = e.pointerType === "touch" ? size * 0.85 : 0;
  303. setPulled(true);
  304. aim(e);
  305. kick();
  306. };
  307. const onMove = (e: PointerEvent) => {
  308. if (!held) return;
  309. aim(e);
  310. kick();
  311. };
  312. // Let go: the spring home starts from the lens's current velocity.
  313. const onUp = () => {
  314. if (!held) return;
  315. held = false;
  316. kick();
  317. };
  318. const onEnter = (e: PointerEvent) => {
  319. if (e.pointerType === "touch") return;
  320. hover = true;
  321. kick();
  322. };
  323. const onLeave = () => {
  324. hover = false;
  325. kick();
  326. };
  327. relayout.current = () => {
  328. findHome();
  329. if (held || frame) return;
  330. p.x = home.x;
  331. p.y = home.y;
  332. if (!hover) p.s = home.s;
  333. render();
  334. };
  335. const onResize = () => relayout.current();
  336. handle.addEventListener("pointerdown", onDown);
  337. handle.addEventListener("pointermove", onMove);
  338. handle.addEventListener("pointerup", onUp);
  339. handle.addEventListener("pointercancel", onUp);
  340. handle.addEventListener("pointerenter", onEnter);
  341. handle.addEventListener("pointerleave", onLeave);
  342. window.addEventListener("resize", onResize);
  343. document.fonts.ready.then(() => relayout.current());
  344. return () => {
  345. cancelAnimationFrame(frame);
  346. unlight();
  347. relayout.current = () => {};
  348. handle.removeEventListener("pointerdown", onDown);
  349. handle.removeEventListener("pointermove", onMove);
  350. handle.removeEventListener("pointerup", onUp);
  351. handle.removeEventListener("pointercancel", onUp);
  352. handle.removeEventListener("pointerenter", onEnter);
  353. handle.removeEventListener("pointerleave", onLeave);
  354. window.removeEventListener("resize", onResize);
  355. };
  356. }, []);
  357. return (
  358. <div ref={wrapRef} className="relative -mx-1 px-1 py-1">
  359. <Title />
  360. <div
  361. ref={orbRef}
  362. aria-hidden
  363. data-droplet
  364. 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]"
  365. >
  366. {map && (
  367. <GlassFilter
  368. blur={0.2}
  369. chroma={0.025}
  370. id={FILTER_ID}
  371. map={map}
  372. saturate={1.05}
  373. />
  374. )}
  375. <div
  376. className="absolute inset-0 overflow-hidden rounded-full bg-[#fbf9f9] dark:bg-[#161b22]"
  377. style={{ filter: map ? `url(#${FILTER_ID})` : undefined }}
  378. >
  379. <div
  380. ref={cloneRef}
  381. className="absolute top-1 left-1 w-max origin-top-left"
  382. data-clone
  383. >
  384. <Title clone />
  385. </div>
  386. </div>
  387. {/* Bubble shading: rim thickness, a glossy specular highlight, and a soft caustic. */}
  388. <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)]" />
  389. <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" />
  390. <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" />
  391. </div>
  392. {/* A generous grab target around the period (the bead itself is tiny). */}
  393. <span
  394. ref={handleRef}
  395. aria-hidden
  396. className="absolute top-0 left-0 z-20 -mt-6 -ml-6 size-12 cursor-grab touch-none rounded-full active:cursor-grabbing"
  397. data-cursor="Pull the period"
  398. data-nodrag
  399. />
  400. <p
  401. aria-hidden
  402. className={cn(
  403. "pointer-events-none mt-3 text-[13px] text-muted transition-opacity duration-500 max-sm:hidden",
  404. pulled && "opacity-0",
  405. )}
  406. >
  407. Psst, the period is liquid glass. Pull it.
  408. </p>
  409. </div>
  410. );
  411. }