hero-title.tsx 15 KB

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