command-palette.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. "use client";
  2. import { usePathname, useRouter } from "next/navigation";
  3. import { useTheme } from "next-themes";
  4. import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
  5. import { LiquidGlass } from "@/components/glass/liquid-glass";
  6. import { useLocale, useT } from "@/components/locale-provider";
  7. import { projects, siteConfig } from "@/config/site";
  8. import { localePath, stripLocale } from "@/lib/i18n";
  9. import { switchTheme } from "@/lib/theme-transition";
  10. import { cn } from "@/lib/utils";
  11. import type { View } from "@/lib/view-store";
  12. type Command = {
  13. id: string;
  14. group: string;
  15. label: string;
  16. hint?: string;
  17. keywords?: string;
  18. icon: ReactNode;
  19. run: () => void;
  20. };
  21. const Arrow = () => (
  22. <svg aria-hidden className="size-4" fill="none" viewBox="0 0 16 16">
  23. <path
  24. d="M5 11 11 5M6 5h5v5"
  25. stroke="currentColor"
  26. strokeLinecap="round"
  27. strokeWidth="1.5"
  28. />
  29. </svg>
  30. );
  31. const Dot = ({ className }: { className?: string }) => (
  32. <span aria-hidden className={cn("size-2 rounded-full", className)} />
  33. );
  34. function score(query: string, text: string) {
  35. if (!query) return 1;
  36. const q = query.toLowerCase();
  37. const t = text.toLowerCase();
  38. if (t.includes(q)) return 2 - t.indexOf(q) / 100;
  39. let i = 0;
  40. for (const ch of t) if (ch === q[i]) i++;
  41. return i === q.length ? 0.5 : 0;
  42. }
  43. export default function CommandPalette({
  44. onClose,
  45. onSelectTab,
  46. }: {
  47. onClose: () => void;
  48. onSelectTab: (id: View | "blog") => void;
  49. }) {
  50. const router = useRouter();
  51. const lang = useLocale();
  52. const { palette: t, projects: projectCopy } = useT();
  53. const pathname = usePathname();
  54. const { resolvedTheme, setTheme } = useTheme();
  55. const [query, setQuery] = useState("");
  56. const [active, setActive] = useState(0);
  57. const [toast, setToast] = useState<string | null>(null);
  58. const inputRef = useRef<HTMLInputElement>(null);
  59. const listRef = useRef<HTMLDivElement>(null);
  60. const commands = useMemo<Command[]>(() => {
  61. const go = (id: View | "blog") => () => {
  62. onSelectTab(id);
  63. onClose();
  64. };
  65. const open = (href: string) => () => {
  66. window.open(href, "_blank", "noopener,noreferrer");
  67. onClose();
  68. };
  69. const fire =
  70. (event: string, view: View = "about") =>
  71. () => {
  72. onSelectTab(view);
  73. onClose();
  74. window.setTimeout(
  75. () => window.dispatchEvent(new CustomEvent(event)),
  76. 450,
  77. );
  78. };
  79. return [
  80. {
  81. id: "all",
  82. group: t.groups.navigate,
  83. label: t.everything,
  84. hint: t.allCards,
  85. icon: <Dot className="bg-glacier" />,
  86. run: go("all"),
  87. },
  88. {
  89. id: "about",
  90. group: t.groups.navigate,
  91. label: t.about,
  92. icon: <Dot className="bg-glacier" />,
  93. run: go("about"),
  94. },
  95. {
  96. id: "work",
  97. group: t.groups.navigate,
  98. label: t.work,
  99. keywords:
  100. "aws amazon finops q artifacts side projects packbook secondself",
  101. icon: <Dot className="bg-ember" />,
  102. run: go("work"),
  103. },
  104. {
  105. id: "blog",
  106. group: t.groups.navigate,
  107. label: t.blog,
  108. keywords: "writing posts",
  109. icon: <Dot className="bg-ink-2" />,
  110. run: go("blog"),
  111. },
  112. ...Object.values(projects).map((p) => ({
  113. id: p.id,
  114. group: t.groups.projects,
  115. label: p.name,
  116. hint: p.linkLabel,
  117. keywords: `${p.kicker} ${projectCopy[p.id as keyof typeof projectCopy].kicker}`,
  118. icon: <Arrow />,
  119. run: open(p.href),
  120. })),
  121. {
  122. id: "github",
  123. group: t.groups.connect,
  124. label: "GitHub",
  125. hint: "@itsEricWu",
  126. icon: <Arrow />,
  127. run: open(siteConfig.links.github),
  128. },
  129. {
  130. id: "linkedin",
  131. group: t.groups.connect,
  132. label: "LinkedIn",
  133. icon: <Arrow />,
  134. run: open(siteConfig.links.linkedin),
  135. },
  136. {
  137. id: "email",
  138. group: t.groups.connect,
  139. label: t.copyEmail,
  140. hint: siteConfig.email,
  141. keywords: "mail contact",
  142. icon: <Dot className="bg-glacier" />,
  143. run: () => {
  144. navigator.clipboard?.writeText(siteConfig.email).then(
  145. () => setToast(t.emailCopied),
  146. () => setToast(siteConfig.email),
  147. );
  148. window.setTimeout(onClose, 900);
  149. },
  150. },
  151. {
  152. id: "theme",
  153. group: t.groups.settings,
  154. label: resolvedTheme === "dark" ? t.lightsOn : t.lightsOff,
  155. keywords: "theme dark light mode",
  156. icon: <Dot className="bg-ink" />,
  157. run: () => {
  158. onClose();
  159. switchTheme(resolvedTheme === "dark" ? "light" : "dark", setTheme, {
  160. x: window.innerWidth / 2,
  161. y: window.innerHeight * 0.2,
  162. });
  163. },
  164. },
  165. {
  166. id: "language",
  167. group: t.groups.settings,
  168. label: t.language,
  169. hint: t.languageHint,
  170. keywords: "language chinese english 语言 中文 英文",
  171. icon: <Dot className="bg-glacier" />,
  172. run: () => {
  173. // The other language is a different root layout: a full load.
  174. window.location.assign(
  175. localePath(lang === "en" ? "zh" : "en", stripLocale(pathname)) +
  176. window.location.hash,
  177. );
  178. },
  179. },
  180. {
  181. id: "bert",
  182. group: t.groups.fun,
  183. label: t.bert,
  184. hint: t.bertHint,
  185. keywords: "dog avatar",
  186. icon: <Dot className="bg-ember" />,
  187. run: fire("eric:bert"),
  188. },
  189. {
  190. id: "mini",
  191. group: t.groups.fun,
  192. label: t.mini,
  193. keywords: "car three",
  194. icon: <Dot className="bg-ember" />,
  195. run: fire("eric:mini"),
  196. },
  197. {
  198. id: "home",
  199. group: t.groups.fun,
  200. label: t.top,
  201. icon: <Dot className="bg-muted" />,
  202. run: () => {
  203. router.push(localePath(lang, "/"));
  204. window.scrollTo({ top: 0, behavior: "smooth" });
  205. onClose();
  206. },
  207. },
  208. ];
  209. }, [
  210. lang,
  211. onClose,
  212. onSelectTab,
  213. pathname,
  214. projectCopy,
  215. resolvedTheme,
  216. router,
  217. setTheme,
  218. t,
  219. ]);
  220. const results = useMemo(
  221. () =>
  222. commands
  223. .map((c) => ({
  224. c,
  225. s: score(query, `${c.label} ${c.keywords ?? ""} ${c.group}`),
  226. }))
  227. .filter((r) => r.s > 0)
  228. .sort((a, b) => b.s - a.s)
  229. .map((r) => r.c),
  230. [commands, query],
  231. );
  232. useEffect(() => {
  233. const previous = document.activeElement as HTMLElement | null;
  234. // Hand focus back only to someone navigating by keyboard; otherwise a
  235. // mouse-clicked control would light up with a focus ring on close.
  236. const restore = previous?.matches?.(":focus-visible") ?? false;
  237. inputRef.current?.focus();
  238. const onKey = (e: KeyboardEvent) => {
  239. if (e.key === "Escape") onClose();
  240. };
  241. window.addEventListener("keydown", onKey);
  242. return () => {
  243. window.removeEventListener("keydown", onKey);
  244. if (restore) previous?.focus?.();
  245. };
  246. }, [onClose]);
  247. useEffect(() => {
  248. listRef.current
  249. ?.querySelector<HTMLElement>(`[data-index="${active}"]`)
  250. ?.scrollIntoView({ block: "nearest" });
  251. }, [active]);
  252. return (
  253. <div
  254. aria-label={t.dialog}
  255. aria-modal="true"
  256. className="fixed inset-0 z-[60] flex items-start justify-center px-3 pt-[12vh]"
  257. role="dialog"
  258. onPointerDown={(e) => {
  259. if (e.target === e.currentTarget) onClose();
  260. }}
  261. >
  262. {/* A sibling, not a parent: refraction nested inside another backdrop filter renders wrong in Chromium. */}
  263. <div
  264. aria-hidden
  265. className="pointer-events-none absolute inset-0 bg-black/20 backdrop-blur-[3px] [animation:fade-in_.3s_ease_both] dark:bg-black/50"
  266. />
  267. <LiquidGlass
  268. className="w-full max-w-[600px] overflow-hidden rounded-[26px] [--glass-tint:color-mix(in_oklab,var(--card)_80%,transparent)] [--lg-blur:24px] [animation:rise_.45s_cubic-bezier(.2,.8,.2,1)_both] dark:[--glass-tint:color-mix(in_oklab,var(--card)_75%,transparent)]"
  269. glass={{
  270. bezel: 22,
  271. thickness: 26,
  272. blur: 10,
  273. chroma: 0.08,
  274. saturate: 1.9,
  275. }}
  276. >
  277. <div className="flex items-center gap-3 border-b border-line px-5">
  278. <svg
  279. aria-hidden
  280. className="size-4 text-muted"
  281. fill="none"
  282. viewBox="0 0 16 16"
  283. >
  284. <circle
  285. cx="7"
  286. cy="7"
  287. r="5"
  288. stroke="currentColor"
  289. strokeWidth="1.5"
  290. />
  291. <path
  292. d="m11 11 3 3"
  293. stroke="currentColor"
  294. strokeLinecap="round"
  295. strokeWidth="1.5"
  296. />
  297. </svg>
  298. <input
  299. ref={inputRef}
  300. aria-activedescendant={
  301. results[active] ? `cmd-${results[active].id}` : undefined
  302. }
  303. aria-controls="cmd-list"
  304. aria-label={t.input}
  305. className="h-14 w-full bg-transparent text-[15px] outline-none placeholder:text-muted"
  306. placeholder={t.placeholder}
  307. value={query}
  308. onChange={(e) => {
  309. setQuery(e.target.value);
  310. setActive(0);
  311. }}
  312. onKeyDown={(e) => {
  313. if (e.key === "ArrowDown") {
  314. e.preventDefault();
  315. setActive((i) => Math.min(results.length - 1, i + 1));
  316. } else if (e.key === "ArrowUp") {
  317. e.preventDefault();
  318. setActive((i) => Math.max(0, i - 1));
  319. } else if (e.key === "Enter") {
  320. e.preventDefault();
  321. results[active]?.run();
  322. }
  323. }}
  324. />
  325. <kbd className="rounded-md border border-line px-1.5 py-0.5 text-[11px] font-medium text-muted">
  326. esc
  327. </kbd>
  328. </div>
  329. <div
  330. ref={listRef}
  331. className="no-scrollbar max-h-[min(420px,56vh)] overflow-y-auto p-2"
  332. id="cmd-list"
  333. role="listbox"
  334. >
  335. {results.length === 0 && (
  336. <p className="px-3 py-8 text-center text-sm text-muted">
  337. {t.empty(query)}
  338. </p>
  339. )}
  340. {results.map((c, i) => {
  341. const header = i === 0 || results[i - 1].group !== c.group;
  342. return (
  343. <div key={c.id}>
  344. {header && !query && (
  345. <p className="eyebrow px-3 pt-3 pb-1">{c.group}</p>
  346. )}
  347. <div
  348. aria-selected={i === active}
  349. className={cn(
  350. "flex cursor-pointer items-center gap-3 rounded-2xl px-3 py-2.5 text-[14px] transition-colors",
  351. i === active
  352. ? "bg-ink/[0.07] text-ink dark:bg-white/[0.08]"
  353. : "text-ink-2",
  354. )}
  355. data-index={i}
  356. id={`cmd-${c.id}`}
  357. role="option"
  358. onClick={c.run}
  359. onPointerMove={() => setActive(i)}
  360. >
  361. <span className="grid size-5 place-items-center text-muted">
  362. {c.icon}
  363. </span>
  364. <span className="flex-1">{c.label}</span>
  365. {c.hint && (
  366. <span className="text-[12px] text-muted">{c.hint}</span>
  367. )}
  368. </div>
  369. </div>
  370. );
  371. })}
  372. </div>
  373. <div className="flex items-center justify-between border-t border-line px-5 py-2.5 text-[12px] text-muted">
  374. <span>{t.help}</span>
  375. <span aria-live="polite">{toast ?? "ericwu.me"}</span>
  376. </div>
  377. </LiquidGlass>
  378. </div>
  379. );
  380. }