globe.tsx 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. "use client";
  2. import type { COBEOptions, Globe } from "cobe";
  3. import { useTheme } from "next-themes";
  4. import { useEffect, useLayoutEffect, useRef, type CSSProperties } from "react";
  5. import { useLocale, useT } from "@/components/locale-provider";
  6. const PURDUE: [number, number] = [40.4237, -86.9212];
  7. const UCLA: [number, number] = [34.0689, -118.4452];
  8. const SEATTLE: [number, number] = [47.6062, -122.3321];
  9. /** Each label sits on the side of its marker that keeps the three apart. */
  10. // Each label's words live in messages/ (globe.labels).
  11. const LABELS: { id: string; place: CSSProperties }[] = [
  12. {
  13. id: "seattle",
  14. place: {
  15. bottom: "anchor(top)",
  16. left: "anchor(center)",
  17. translate: "-50% -7px",
  18. },
  19. },
  20. {
  21. id: "ucla",
  22. place: {
  23. top: "anchor(center)",
  24. right: "anchor(left)",
  25. translate: "-7px -50%",
  26. },
  27. },
  28. {
  29. id: "purdue",
  30. place: {
  31. top: "anchor(bottom)",
  32. left: "anchor(center)",
  33. translate: "-50% 7px",
  34. },
  35. },
  36. ];
  37. type Palette = Pick<
  38. COBEOptions,
  39. | "dark"
  40. | "diffuse"
  41. | "mapBrightness"
  42. | "mapBaseBrightness"
  43. | "baseColor"
  44. | "markerColor"
  45. | "glowColor"
  46. | "arcColor"
  47. >;
  48. const PALETTES: Record<"light" | "dark", Palette> = {
  49. light: {
  50. dark: 0,
  51. diffuse: 1.2,
  52. mapBrightness: 7,
  53. mapBaseBrightness: 0,
  54. baseColor: [1, 1, 1],
  55. markerColor: [0.16, 0.53, 0.87],
  56. glowColor: [0.98, 0.9, 0.93],
  57. arcColor: [0.85, 0.28, 0.48],
  58. },
  59. dark: {
  60. dark: 1,
  61. diffuse: 1.4,
  62. mapBrightness: 4.5,
  63. mapBaseBrightness: 0.02,
  64. baseColor: [0.15, 0.2, 0.27],
  65. markerColor: [0.55, 0.79, 1],
  66. glowColor: [0.12, 0.22, 0.32],
  67. arcColor: [1, 0.62, 0.74],
  68. },
  69. };
  70. /** cobe's angles that put a place at the center of the view. */
  71. const facing = (lat: number, lon: number) => [
  72. Math.PI - ((lon * Math.PI) / 180 - Math.PI / 2),
  73. (lat * Math.PI) / 180,
  74. ];
  75. const [HOME_PHI, HOME_THETA] = facing(40, -104);
  76. const TAU = Math.PI * 2;
  77. /**
  78. * Purdue → UCLA → Seattle on a dotted WebGL globe (cobe, ~6KB, loaded when
  79. * visible). It rests on North America with a slow sway; spin it and it glides
  80. * back.
  81. */
  82. export function GlobeCard() {
  83. const { globe: t } = useT();
  84. const lang = useLocale();
  85. // Chinese may break between any two characters, and Safari wouldn't break
  86. // this one at all, so on small tiles it breaks where the English does:
  87. // before the last stop.
  88. const lastStop = t.title.lastIndexOf(" ") + 1;
  89. const wrapRef = useRef<HTMLDivElement>(null);
  90. const canvasRef = useRef<HTMLCanvasElement>(null);
  91. const globeRef = useRef<Globe | null>(null);
  92. const { resolvedTheme } = useTheme();
  93. const palette = PALETTES[resolvedTheme === "dark" ? "dark" : "light"];
  94. const paletteRef = useRef(palette);
  95. const ready = resolvedTheme !== undefined;
  96. // A theme switch recolours the globe in place, in the same frame as the
  97. // page: rebuilding it left a frame of the old globe, then an empty card.
  98. useLayoutEffect(() => {
  99. paletteRef.current = palette;
  100. globeRef.current?.update(palette);
  101. }, [palette]);
  102. useEffect(() => {
  103. const wrap = wrapRef.current;
  104. const canvas = canvasRef.current;
  105. if (!wrap || !canvas || !ready) return;
  106. let globe: Globe | null = null;
  107. let frame = 0;
  108. let visible = false;
  109. let disposed = false;
  110. let phi = HOME_PHI;
  111. let theta = HOME_THETA * 0.7;
  112. let spin = 0;
  113. let dragging = false;
  114. let lastX = 0;
  115. let lastY = 0;
  116. const loop = () => {
  117. frame = 0;
  118. if (!globe || !visible || document.hidden) return;
  119. if (!dragging) {
  120. // Coast on the fling, then ease back to the home view along the shortest way round.
  121. const goal = HOME_PHI + 0.16 * Math.sin(performance.now() / 5200);
  122. const delta = ((((goal - phi) % TAU) + TAU * 1.5) % TAU) - Math.PI;
  123. phi += spin + delta * 0.012 * (1 - Math.min(1, Math.abs(spin) * 40));
  124. theta += (HOME_THETA * 0.7 - theta) * 0.02;
  125. spin *= 0.95;
  126. }
  127. const size = wrap.clientWidth;
  128. globe.update({ phi, theta, width: size * 2, height: size * 2 });
  129. frame = requestAnimationFrame(loop);
  130. };
  131. const start = () => {
  132. if (!frame) frame = requestAnimationFrame(loop);
  133. };
  134. const create = async () => {
  135. if (globe || disposed) return;
  136. const { default: createGlobe } = await import("cobe");
  137. if (disposed) return;
  138. const size = wrap.clientWidth;
  139. globe = createGlobe(canvas, {
  140. devicePixelRatio: 2,
  141. width: size * 2,
  142. height: size * 2,
  143. phi,
  144. theta,
  145. mapSamples: 14000,
  146. ...paletteRef.current,
  147. markers: [
  148. { location: SEATTLE, size: 0.075, id: "seattle" },
  149. { location: UCLA, size: 0.05, id: "ucla" },
  150. { location: PURDUE, size: 0.05, id: "purdue" },
  151. ],
  152. arcs: [
  153. { from: PURDUE, to: UCLA, id: "purdue-ucla" },
  154. { from: UCLA, to: SEATTLE, id: "ucla-seattle" },
  155. ],
  156. arcWidth: 0.7,
  157. arcHeight: 0.28,
  158. markerElevation: 0.015,
  159. scale: 1.3,
  160. });
  161. globeRef.current = globe;
  162. canvas.style.opacity = "1";
  163. start();
  164. };
  165. const io = new IntersectionObserver(
  166. ([entry]) => {
  167. visible = entry.isIntersecting;
  168. if (visible) {
  169. create();
  170. start();
  171. }
  172. },
  173. { rootMargin: "120px" },
  174. );
  175. io.observe(wrap);
  176. const onDown = (e: PointerEvent) => {
  177. dragging = true;
  178. lastX = e.clientX;
  179. lastY = e.clientY;
  180. canvas.setPointerCapture(e.pointerId);
  181. };
  182. const onMove = (e: PointerEvent) => {
  183. if (!dragging) return;
  184. const dx = e.clientX - lastX;
  185. const dy = e.clientY - lastY;
  186. lastX = e.clientX;
  187. lastY = e.clientY;
  188. phi += dx * 0.008;
  189. theta = Math.max(-0.4, Math.min(1.1, theta + dy * 0.004));
  190. spin = dx * 0.0009;
  191. };
  192. const onUp = () => {
  193. dragging = false;
  194. };
  195. const onVisibility = () => !document.hidden && start();
  196. canvas.addEventListener("pointerdown", onDown);
  197. canvas.addEventListener("pointermove", onMove);
  198. canvas.addEventListener("pointerup", onUp);
  199. canvas.addEventListener("pointercancel", onUp);
  200. document.addEventListener("visibilitychange", onVisibility);
  201. return () => {
  202. disposed = true;
  203. cancelAnimationFrame(frame);
  204. io.disconnect();
  205. globe?.destroy();
  206. globeRef.current = null;
  207. canvas.removeEventListener("pointerdown", onDown);
  208. canvas.removeEventListener("pointermove", onMove);
  209. canvas.removeEventListener("pointerup", onUp);
  210. canvas.removeEventListener("pointercancel", onUp);
  211. document.removeEventListener("visibilitychange", onVisibility);
  212. };
  213. }, [ready]);
  214. return (
  215. <div className="@container relative h-full overflow-hidden">
  216. <div className="absolute top-5 left-5 z-10 leading-tight sm:top-6 sm:left-6">
  217. <p className="font-display text-[15px] leading-snug font-semibold tracking-[-0.005em] @min-[250px]:text-[17px]">
  218. {lang === "zh" ? (
  219. <>
  220. {t.title.slice(0, lastStop)}
  221. <br className="@min-[250px]:hidden" />
  222. {t.title.slice(lastStop)}
  223. </>
  224. ) : (
  225. t.title
  226. )}
  227. </p>
  228. <p className="text-[12px] text-muted @max-[220px]:hidden">{t.drag}</p>
  229. </div>
  230. {/* The globe's rim sits just under the title. On small tiles it leans
  231. right, so the UCLA label has room on its left. */}
  232. <div
  233. ref={wrapRef}
  234. className="absolute top-[30%] right-[-20%] left-[-8%] aspect-square @min-[220px]:top-[22%] @min-[220px]:right-[-14%] @min-[220px]:left-[-14%]"
  235. >
  236. <canvas
  237. ref={canvasRef}
  238. aria-label={t.aria}
  239. className="size-full cursor-grab opacity-0 transition-opacity duration-1000 active:cursor-grabbing"
  240. data-cursor={t.cursor}
  241. role="img"
  242. />
  243. {LABELS.map((l) => (
  244. <span
  245. key={l.id}
  246. className="globe-label lg pointer-events-none absolute rounded-full px-2 py-0.5 text-[10.5px] font-medium whitespace-nowrap sm:text-[11px]"
  247. style={
  248. {
  249. positionAnchor: `--cobe-${l.id}`,
  250. ...l.place,
  251. opacity: `var(--cobe-visible-${l.id}, 0)`,
  252. } as CSSProperties
  253. }
  254. >
  255. {t.labels[l.id]}
  256. </span>
  257. ))}
  258. </div>
  259. </div>
  260. );
  261. }