command-palette.tsx 11 KB

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