site-nav.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. "use client";
  2. import dynamic from "next/dynamic";
  3. import { usePathname, useRouter } from "next/navigation";
  4. import { useTheme } from "next-themes";
  5. import { useCallback, useEffect, useRef, useState } from "react";
  6. import { LiquidGlass, useGlassLight } from "@/components/glass/liquid-glass";
  7. import { useLocale, useT } from "@/components/locale-provider";
  8. import { useShortcut } from "@/components/nav/shortcut";
  9. import { htmlLang, localePath, stripLocale, type Locale } from "@/lib/i18n";
  10. import { springs } from "@/lib/motion";
  11. import { switchTheme } from "@/lib/theme-transition";
  12. import { cn } from "@/lib/utils";
  13. import { setView, useView, type View } from "@/lib/view-store";
  14. const CommandPalette = dynamic(() => import("./command-palette"), {
  15. ssr: false,
  16. });
  17. type TabId = View | "blog";
  18. // In order; the labels live in messages/ (nav.tabs).
  19. const TABS: TabId[] = ["all", "about", "work", "blog"];
  20. export function SiteNav() {
  21. const lang = useLocale();
  22. const t = useT();
  23. // The path without its language, so both languages share the logic below.
  24. const pathname = stripLocale(usePathname());
  25. const router = useRouter();
  26. const view = useView();
  27. const onHome = pathname === "/";
  28. const activeId = pathname.startsWith("/blog") ? "blog" : onHome ? view : null;
  29. const activeIndex = TABS.findIndex((id) => id === activeId);
  30. const [paletteOpen, setPaletteOpen] = useState(false);
  31. const shortcut = useShortcut();
  32. const select = useCallback(
  33. (id: TabId) => {
  34. if (id === "blog") {
  35. if (pathname !== "/blog") router.push(localePath(lang, "/blog"));
  36. return;
  37. }
  38. if (onHome) {
  39. setView(id);
  40. window.scrollTo({ top: 0, behavior: "smooth" });
  41. } else {
  42. setView(id, { updateUrl: false });
  43. const home = localePath(lang, "/");
  44. router.push(id === "all" ? home : `${home}#${id}`);
  45. }
  46. },
  47. [lang, onHome, pathname, router],
  48. );
  49. useEffect(() => {
  50. const onKey = (e: KeyboardEvent) => {
  51. const typing =
  52. e.target instanceof HTMLElement &&
  53. (e.target.isContentEditable ||
  54. ["INPUT", "TEXTAREA", "SELECT"].includes(e.target.tagName));
  55. if ((e.key === "k" || e.key === "K") && (e.metaKey || e.ctrlKey)) {
  56. e.preventDefault();
  57. setPaletteOpen((open) => !open);
  58. } else if (e.key === "/" && !typing) {
  59. e.preventDefault();
  60. setPaletteOpen(true);
  61. }
  62. };
  63. window.addEventListener("keydown", onKey);
  64. return () => window.removeEventListener("keydown", onKey);
  65. }, []);
  66. return (
  67. <>
  68. <header className="pointer-events-none fixed inset-x-0 bottom-[max(14px,env(safe-area-inset-bottom))] z-50 flex justify-center px-3 sm:top-4 sm:bottom-auto">
  69. <LiquidGlass
  70. data-steady-light
  71. className="pointer-events-auto flex items-center gap-1 rounded-full p-1.5 [--glass-tint:rgb(255_255_255/0.5)] dark:[--glass-tint:rgb(16_20_26/0.55)]"
  72. glass={{ chroma: 0.1, blur: 3, saturate: 1.8 }}
  73. >
  74. <Tabs
  75. activeIndex={activeIndex}
  76. labels={TABS.map((id) => t.nav.tabs[id])}
  77. sections={t.nav.sections}
  78. onSelect={select}
  79. />
  80. <SearchButton
  81. label={t.nav.search}
  82. shortcut={shortcut}
  83. onOpen={() => setPaletteOpen(true)}
  84. />
  85. <LanguageButton lang={lang} path={pathname} />
  86. <ThemeButton />
  87. </LiquidGlass>
  88. </header>
  89. {paletteOpen && (
  90. <CommandPalette
  91. onClose={() => setPaletteOpen(false)}
  92. onSelectTab={select}
  93. />
  94. )}
  95. </>
  96. );
  97. }
  98. function Tabs({
  99. activeIndex,
  100. labels,
  101. sections,
  102. onSelect,
  103. }: {
  104. activeIndex: number;
  105. labels: string[];
  106. sections: string;
  107. onSelect: (id: TabId) => void;
  108. }) {
  109. const listRef = useRef<HTMLDivElement>(null);
  110. const prevIndex = useRef(activeIndex);
  111. const drag = useRef<{
  112. startX: number;
  113. lastX: number;
  114. lastT: number;
  115. v: number;
  116. moved: boolean;
  117. } | null>(null);
  118. // Nested backdrop filters are unreliable in Chromium, so the pill sits behind
  119. // the labels as lit glass; only the bar itself refracts the page.
  120. const dropletRef = useRef<HTMLSpanElement>(null);
  121. useGlassLight(dropletRef);
  122. // Liquid hop between tabs: stretch along the path, squash, then settle with a spring.
  123. useEffect(() => {
  124. const el = dropletRef.current;
  125. const from = prevIndex.current;
  126. prevIndex.current = activeIndex;
  127. if (!el || activeIndex < 0) return;
  128. el.style.transform = `translateX(${activeIndex * 100}%)`;
  129. el.style.opacity = "1";
  130. if (from < 0 || from === activeIndex) return;
  131. const dist = Math.abs(activeIndex - from);
  132. const stretch = 1 + Math.min(0.55, dist * 0.22);
  133. const s = springs.wobble();
  134. el.animate(
  135. [
  136. { transform: `translateX(${from * 100}%) scale(1, 1)` },
  137. {
  138. transform: `translateX(${((from + activeIndex) / 2) * 100}%) scale(${stretch}, ${2 - stretch})`,
  139. offset: 0.45,
  140. },
  141. { transform: `translateX(${activeIndex * 100}%) scale(1, 1)` },
  142. ],
  143. { duration: Math.max(420, s.duration), easing: s.easing },
  144. );
  145. }, [activeIndex]);
  146. const indexAt = (clientX: number) => {
  147. const list = listRef.current;
  148. if (!list) return activeIndex;
  149. const r = list.getBoundingClientRect();
  150. const w = r.width / TABS.length;
  151. return Math.max(
  152. 0,
  153. Math.min(TABS.length - 1, Math.floor((clientX - r.left) / w)),
  154. );
  155. };
  156. // Press and drag the droplet across the bar, like the iOS 26 tab bar.
  157. const onPointerDown = (e: React.PointerEvent) => {
  158. if (e.button !== 0) return;
  159. drag.current = {
  160. startX: e.clientX,
  161. lastX: e.clientX,
  162. lastT: performance.now(),
  163. v: 0,
  164. moved: false,
  165. };
  166. dropletRef.current?.style.setProperty("--press", "1");
  167. };
  168. const onPointerMove = (e: React.PointerEvent) => {
  169. const d = drag.current;
  170. const el = dropletRef.current;
  171. const list = listRef.current;
  172. if (!d || !el || !list) return;
  173. if (!d.moved && Math.abs(e.clientX - d.startX) < 6) return;
  174. if (!d.moved) {
  175. d.moved = true;
  176. list.setPointerCapture(e.pointerId);
  177. el.getAnimations().forEach((a) => a.cancel());
  178. }
  179. const now = performance.now();
  180. d.v =
  181. 0.8 * d.v + 0.2 * ((e.clientX - d.lastX) / Math.max(1, now - d.lastT));
  182. d.lastX = e.clientX;
  183. d.lastT = now;
  184. const r = list.getBoundingClientRect();
  185. const w = r.width / TABS.length;
  186. const x = Math.max(0, Math.min(r.width - w, e.clientX - r.left - w / 2));
  187. const stretch = 1 + Math.min(0.45, Math.abs(d.v) * 0.18);
  188. el.style.opacity = "1";
  189. el.style.transform = `translateX(${(x / w) * 100}%) scale(${stretch * 1.06}, ${(2 - stretch) * 1.06})`;
  190. };
  191. const onPointerUp = (e: React.PointerEvent) => {
  192. const d = drag.current;
  193. drag.current = null;
  194. dropletRef.current?.style.removeProperty("--press");
  195. if (!d?.moved) return;
  196. const index = indexAt(e.clientX);
  197. const el = dropletRef.current;
  198. if (el) {
  199. const current = el.style.transform;
  200. const s = springs.wobble();
  201. el.style.transform = `translateX(${index * 100}%)`;
  202. el.animate([{ transform: current }, { transform: el.style.transform }], {
  203. duration: s.duration,
  204. easing: s.easing,
  205. });
  206. }
  207. prevIndex.current = index;
  208. onSelect(TABS[index]);
  209. };
  210. return (
  211. <div
  212. ref={listRef}
  213. aria-label={sections}
  214. className="relative flex touch-pan-y select-none"
  215. role="tablist"
  216. onPointerCancel={onPointerUp}
  217. onPointerDown={onPointerDown}
  218. onPointerMove={onPointerMove}
  219. onPointerUp={onPointerUp}
  220. >
  221. {TABS.map((tab, i) => (
  222. <button
  223. key={tab}
  224. aria-selected={i === activeIndex}
  225. className={cn(
  226. "relative z-10 h-10 w-[58px] rounded-full text-[13px] font-medium transition-[color,scale] duration-300 sm:w-[76px] sm:text-[14px]",
  227. i === activeIndex
  228. ? "scale-[1.06] text-ink"
  229. : "text-muted hover:text-ink",
  230. )}
  231. role="tab"
  232. type="button"
  233. onClick={() => {
  234. if (drag.current?.moved) return;
  235. onSelect(tab);
  236. }}
  237. >
  238. {labels[i]}
  239. </button>
  240. ))}
  241. <span
  242. ref={dropletRef}
  243. aria-hidden
  244. className="lg pointer-events-none absolute inset-y-0 left-0 z-0 w-[58px] rounded-full shadow-[0_6px_16px_-8px_rgb(40_20_30/0.35)] [--glass-tint:rgb(255_255_255/0.75)] transition-[scale] duration-300 [--lg-blur:0px] [backdrop-filter:none] [scale:calc(1+var(--press,0)*0.12)] sm:w-[76px] dark:[--glass-tint:rgb(255_255_255/0.12)]"
  245. style={{
  246. transform: `translateX(${Math.max(0, activeIndex) * 100}%)`,
  247. opacity: activeIndex < 0 ? 0 : 1,
  248. }}
  249. >
  250. <span className="lg-caustic" />
  251. </span>
  252. </div>
  253. );
  254. }
  255. /** Opens the command palette; its shortcut lives in the hover label and the footer. */
  256. function SearchButton({
  257. label,
  258. shortcut,
  259. onOpen,
  260. }: {
  261. label: string;
  262. shortcut: string;
  263. onOpen: () => void;
  264. }) {
  265. const ref = useRef<HTMLButtonElement>(null);
  266. useGlassLight(ref);
  267. return (
  268. <button
  269. ref={ref}
  270. aria-keyshortcuts="Meta+K Control+K"
  271. aria-label={label}
  272. className="lg hidden size-10 place-items-center rounded-full md:grid"
  273. data-cursor={`${label} ${shortcut}`}
  274. type="button"
  275. onClick={onOpen}
  276. >
  277. <span className="lg-caustic" />
  278. <svg
  279. aria-hidden
  280. className="size-[17px]"
  281. fill="none"
  282. stroke="currentColor"
  283. strokeLinecap="round"
  284. strokeWidth="2"
  285. viewBox="0 0 24 24"
  286. >
  287. <circle cx="10.5" cy="10.5" r="6.5" />
  288. <path d="m15.5 15.5 4.5 4.5" />
  289. </svg>
  290. </button>
  291. );
  292. }
  293. /** Opens this page in the other language; its label is written in that language. */
  294. function LanguageButton({ lang, path }: { lang: Locale; path: string }) {
  295. const { nav } = useT();
  296. const ref = useRef<HTMLAnchorElement>(null);
  297. const other: Locale = lang === "en" ? "zh" : "en";
  298. useGlassLight(ref);
  299. return (
  300. <a
  301. ref={ref}
  302. aria-label={nav.switchLabel}
  303. className="lg grid size-10 place-items-center rounded-full text-[13px] font-semibold max-[340px]:hidden"
  304. data-cursor={nav.switchCursor}
  305. href={localePath(other, path)}
  306. hrefLang={htmlLang[other]}
  307. lang={htmlLang[other]}
  308. onClick={(e) => {
  309. // Keep the home grid's view (its hash) across the switch.
  310. e.currentTarget.href = localePath(other, path) + window.location.hash;
  311. }}
  312. >
  313. <span aria-hidden className="lg-caustic" />
  314. <span aria-hidden>{nav.switchShort}</span>
  315. </a>
  316. );
  317. }
  318. function ThemeButton() {
  319. const { nav } = useT();
  320. const { resolvedTheme, setTheme } = useTheme();
  321. const ref = useRef<HTMLButtonElement>(null);
  322. useGlassLight(ref);
  323. return (
  324. <button
  325. ref={ref}
  326. aria-label={nav.theme}
  327. className="lg grid size-10 place-items-center rounded-full"
  328. data-cursor={nav.lights}
  329. type="button"
  330. onClick={(e) => {
  331. const r = e.currentTarget.getBoundingClientRect();
  332. switchTheme(resolvedTheme === "dark" ? "light" : "dark", setTheme, {
  333. x: r.left + r.width / 2,
  334. y: r.top + r.height / 2,
  335. });
  336. }}
  337. >
  338. <span className="lg-caustic" />
  339. <svg aria-hidden className="size-[18px]" fill="none" viewBox="0 0 24 24">
  340. <mask id="theme-moon-mask">
  341. <rect fill="white" height="24" width="24" />
  342. <circle
  343. className="origin-center translate-x-[9px] -translate-y-[9px] transition-transform duration-500 ease-out dark:translate-x-0 dark:translate-y-0"
  344. cx="17"
  345. cy="7"
  346. fill="black"
  347. r="6"
  348. />
  349. </mask>
  350. <circle
  351. className="origin-center scale-[0.55] transition-transform duration-500 ease-out dark:scale-100"
  352. cx="12"
  353. cy="12"
  354. fill="currentColor"
  355. mask="url(#theme-moon-mask)"
  356. r="8"
  357. />
  358. <g
  359. className="origin-center stroke-current transition-[opacity,rotate] duration-500 dark:rotate-45 dark:opacity-0"
  360. strokeLinecap="round"
  361. strokeWidth="2"
  362. >
  363. <path d="M12 1.5v2.2M12 20.3v2.2M1.5 12h2.2M20.3 12h2.2M4.6 4.6l1.5 1.5M17.9 17.9l1.5 1.5M4.6 19.4l1.5-1.5M17.9 6.1l1.5-1.5" />
  364. </g>
  365. </svg>
  366. </button>
  367. );
  368. }