hero-title.tsx 16 KB

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