command-palette.tsx 11 KB

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