hero-title.tsx 16 KB

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