hero-title.tsx 15 KB

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