command-palette.tsx 11 KB

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