🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
feat(ui): Cmd/Ctrl+K command palette and a keyboard shortcut sheet (#1259)
Goldflag58b236d7cfb5
diff --git a/client/src/app/Providers.tsx b/client/src/app/Providers.tsxindex e7d7ecb46..84b587d17 100644--- a/client/src/app/Providers.tsx+++ b/client/src/app/Providers.tsx@@ -15,6 +15,7 @@ import Script from "next/script";import { NuqsAdapter } from "nuqs/adapters/next/app";import { useEffect } from "react";import { AuthenticationGuard } from "../components/AuthenticationGuard";+import { CommandPalette } from "../components/command-palette/CommandPalette";import { OrganizationInitializer } from "../components/OrganizationInitializer";import { Toaster } from "../components/ui/sonner";import { VersionCheck } from "../components/VersionCheck";@@ -75,6 +76,8 @@ export function Providers({ children }: { children: React.ReactNode }) {<OrganizationInitializer /><AuthenticationGuard />{children}+ {/* ⌘K palette and "?" shortcut sheet; renders nothing for signed-out visitors. */}+ <CommandPalette /><VersionCheck /></QueryProvider><Toaster />diff --git a/client/src/app/[site]/components/Sidebar/Sidebar.tsx b/client/src/app/[site]/components/Sidebar/Sidebar.tsxindex 0131e44d5..d8cb23538 100644--- a/client/src/app/[site]/components/Sidebar/Sidebar.tsx+++ b/client/src/app/[site]/components/Sidebar/Sidebar.tsx@@ -23,6 +23,7 @@ import { useExtracted } from "next-intl";import { usePathname, useSearchParams } from "next/navigation";import { Suspense } from "react";import { useGetSite } from "../../../../api/admin/hooks/useSites";+import { CommandPaletteTrigger } from "../../../../components/command-palette/CommandPaletteTrigger";import { Sidebar as SidebarComponents } from "../../../../components/sidebar/Sidebar";import { SiteSettings } from "../../../../components/SiteSettings/SiteSettings";import { useAppEnv } from "../../../../hooks/useIsProduction";@@ -71,6 +72,8 @@ function SidebarContent() {<div className="w-56 bg-neutral-50 border-r border-neutral-150 dark:bg-neutral-900 dark:border-neutral-850 flex flex-col h-dvh"><div className="flex flex-col p-3 border-b border-neutral-200 dark:border-neutral-800"><SiteSelector />+ {/* Keyboard-first, so desktop only (this sidebar also renders in the mobile sheet). */}+ {!embed && <CommandPaletteTrigger className="mt-2 hidden md:flex" />}</div><div className="flex min-h-0 flex-1 flex-col overflow-y-auto p-3 pt-1"><div className="mt-2">diff --git a/client/src/components/command-palette/CommandPalette.test.tsx b/client/src/components/command-palette/CommandPalette.test.tsxnew file mode 100644index 000000000..31a7550d0--- /dev/null+++ b/client/src/components/command-palette/CommandPalette.test.tsx@@ -0,0 +1,414 @@+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { MotionGlobalConfig } from "framer-motion";+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";++import { useStore } from "@/lib/store";+import { CommandPalette } from "./CommandPalette";+import { CommandPaletteTrigger } from "./CommandPaletteTrigger";+import { usePaletteOverlay } from "./store";++const mocks = vi.hoisted(() => ({+ pathname: "/12/main",+ signedIn: true,+ push: vi.fn(),+ setTheme: vi.fn(),+}));++vi.mock("next-intl", () => ({+ useExtracted: () => (message: string, values?: Record<string, string | number>) =>+ values+ ? message+ .replace(/\{(\w+), plural, one \{([^}]*)\} other \{([^}]*)\}\}/g, (_, key, one, other) =>+ String(values[key] === 1 ? one : other).replace("#", String(values[key]))+ )+ .replace(/\{(\w+)\}/g, (_, key) => String(values[key] ?? `{${key}}`))+ : message,+}));++vi.mock("next/navigation", () => ({+ usePathname: () => mocks.pathname,+ useRouter: () => ({ push: mocks.push }),+}));++vi.mock("next-themes", () => ({ useTheme: () => ({ theme: "dark", setTheme: mocks.setTheme }) }));++vi.mock("@uidotdev/usehooks", () => ({ useWindowSize: () => ({ width: 1280, height: 800 }) }));++vi.mock("@/lib/auth", () => ({+ authClient: {+ useSession: () => ({ data: mocks.signedIn ? { user: { id: "user-1" } } : null }),+ useActiveOrganization: () => ({ data: { id: "org-1" } }),+ },+}));++vi.mock("@/lib/subscription/useStripeSubscription", () => ({+ useStripeSubscription: () => ({ data: undefined, isLoading: false }),+}));++vi.mock("@/api/admin/hooks/useSites", () => ({+ useGetSite: () => ({ data: { siteId: 12, name: "rybbit.com", domain: "rybbit.com", type: "web" } }),+ useGetSitesFromOrg: () => ({+ data: {+ sites: [+ { siteId: 12, name: "rybbit.com", domain: "rybbit.com" },+ { siteId: 13, name: "Docs", domain: "docs.rybbit.com" },+ ],+ },+ }),+}));++vi.mock("@/api/admin/hooks/useOrganizations", () => ({+ useUserOrganizations: () => ({ data: [{ id: "org-1", role: "owner" }] }),+}));++vi.mock("@/api/analytics/hooks/goals/useGetGoals", () => ({+ useGetGoals: () => ({+ data: { data: [{ goalId: 1, name: "Signed up", goalType: "path", config: { pathPattern: "/welcome" } }] },+ }),+}));++vi.mock("@/api/analytics/hooks/funnels/useGetFunnels", () => ({+ useGetFunnels: () => ({ data: [{ id: 3, name: "Checkout", steps: [{}, {}, {}] }] }),+}));++vi.mock("@/api/analytics/hooks/useDashboards", () => ({ useGetDashboards: () => ({ data: [] }) }));++const pressCtrlK = (target: Element = document.body) =>+ fireEvent.keyDown(target, { key: "k", code: "KeyK", ctrlKey: true });++const openPalette = async () => {+ pressCtrlK();+ return screen.findByRole("dialog", { name: "Command palette" });+};++const search = (dialog: HTMLElement, query: string) => {+ const input = within(dialog).getByRole("combobox");+ fireEvent.change(input, { target: { value: query } });+ return input;+};++const optionNames = (dialog: HTMLElement) =>+ within(dialog)+ .getAllByRole("option")+ .map(option => option.getAttribute("aria-label"));++// jsdom has no layout: stack the list's entries 36px apart in a list that shows ten.+const ROW_HEIGHT = 36;+const mockListLayout = () => {+ const box = (top: number, height: number) =>+ ({+ top,+ bottom: top + height,+ left: 0,+ right: 560,+ width: 560,+ height,+ x: 0,+ y: top,+ toJSON: () => ({}),+ }) as DOMRect;++ vi.spyOn(Element.prototype, "getBoundingClientRect").mockImplementation(function (this: Element) {+ if (this.hasAttribute("cmdk-list")) return box(0, ROW_HEIGHT * 10);+ if (this.hasAttribute("data-entry")) {+ const siblings = Array.from(this.parentElement?.querySelectorAll(":scope > [data-entry]") ?? []);+ return box(siblings.indexOf(this) * ROW_HEIGHT, ROW_HEIGHT);+ }+ return box(0, 0);+ });+};++beforeAll(() => {+ MotionGlobalConfig.skipAnimations = true;+});++beforeEach(() => {+ mocks.pathname = "/12/main";+ mocks.signedIn = true;+ vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ );+ vi.stubGlobal(+ "matchMedia",+ (query: string) =>+ ({+ matches: false,+ media: query,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ }) as unknown as MediaQueryList+ );+ Element.prototype.scrollIntoView = vi.fn();+});++afterEach(() => {+ cleanup();+ usePaletteOverlay.setState({ overlay: null });+ window.history.replaceState(null, "", "/");+ Reflect.deleteProperty(window.navigator, "platform");+ vi.clearAllMocks();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++describe("CommandPalette", () => {+ it("opens with Ctrl+K off Apple platforms and focuses the search", async () => {+ render(<CommandPalette />);+ expect(screen.queryByRole("dialog")).toBeNull();++ const dialog = await openPalette();++ await waitFor(() => expect(document.activeElement).toBe(within(dialog).getByRole("combobox")));+ });++ it("uses ⌘K on a Mac, and the same chord closes it again", async () => {+ Object.defineProperty(window.navigator, "platform", { value: "MacIntel", configurable: true });+ render(<CommandPalette />);++ pressCtrlK();+ expect(screen.queryByRole("dialog")).toBeNull();++ fireEvent.keyDown(document.body, { key: "k", code: "KeyK", metaKey: true });+ const dialog = await screen.findByRole("dialog", { name: "Command palette" });++ // From inside the search field too.+ fireEvent.keyDown(within(dialog).getByRole("combobox"), { key: "k", code: "KeyK", metaKey: true });+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ });++ it("lists the site's sections under the sidebar's rules, its goals and funnels, and the other sites", async () => {+ render(<CommandPalette />);+ const dialog = await openPalette();+ const names = optionNames(dialog);++ expect(names).toContain("Sessions, rybbit.com");+ expect(names).toContain("Main, rybbit.com, Current");+ // Cloud-only sections stay hidden on a self-hosted build, as in the sidebar.+ expect(names).not.toContain("Pages, rybbit.com");+ expect(names).not.toContain("Query, rybbit.com");+ // The open site is not offered as a site to switch to.+ expect(names).toContain("Docs, docs.rybbit.com, Switch site");+ expect(names.some(name => name?.startsWith("rybbit.com"))).toBe(false);+ expect(names).toContain("Signed up, /welcome, Goals");+ expect(names).toContain("Checkout, 3 steps, Funnels");+ expect(names).toContain("Organization, Navigate");+ expect(names).toContain("Dark, Theme, Current");+ for (const heading of ["rybbit.com", "Switch site", "Goals", "Funnels", "Date range", "Navigate", "Theme"]) {+ expect(within(dialog).getAllByText(heading).length).toBeGreaterThan(0);+ }+ });++ it("ranks as the query changes and runs the top match with Enter", async () => {+ render(<CommandPalette />);+ const dialog = await openPalette();++ const input = search(dialog, "ses");++ expect(optionNames(dialog)[0]).toBe("Sessions, rybbit.com");+ // Ranked results drop the headings; each row shows its group instead.+ expect(within(dialog).queryByText("Switch site")).toBeNull();+ await waitFor(() => expect(within(dialog).getAllByRole("option")[0].getAttribute("aria-selected")).toBe("true"));++ fireEvent.keyDown(input, { key: "Enter" });++ expect(mocks.push).toHaveBeenCalledWith("/12/sessions");+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ });++ it("glides only rows that were on screen; the rest mount in place", async () => {+ mockListLayout();+ render(<CommandPalette />);+ const dialog = await openPalette();+ const option = (name: string) => within(dialog).getByRole("option", { name });+ const list = within(dialog).getByRole("listbox");++ // Grouped view: Sessions is the fourth entry, on screen. Docs, under+ // "Switch site", is the fifteenth: below the fold.+ const sessions = option("Sessions, rybbit.com");+ const docs = option("Docs, docs.rybbit.com, Switch site");+ list.scrollTop = 120;++ search(dialog, "s");++ // Sessions keeps its element, so it glides from where it was drawn...+ expect(option("Sessions, rybbit.com")).toBe(sessions);+ // ...but Docs was never visible: a fresh element lands in its new slot.+ expect(option("Docs, docs.rybbit.com, Switch site")).not.toBe(docs);+ expect(list.scrollTop).toBe(0);+ });++ it("shows an empty state when nothing matches", async () => {+ render(<CommandPalette />);+ const dialog = await openPalette();++ search(dialog, "zzzz");++ expect(within(dialog).queryAllByRole("option")).toHaveLength(0);+ expect(within(dialog).getAllByText("No results").length).toBeGreaterThan(0);+ // Screen readers hear it once typing settles.+ await waitFor(() => expect(within(dialog).getByRole("status").textContent).toBe("No results"));+ });++ it("announces the result count once typing settles", async () => {+ render(<CommandPalette />);+ const dialog = await openPalette();+ const status = within(dialog).getByRole("status");+ expect(status.textContent).toBe("");++ search(dialog, "checkout");+ await waitFor(() => expect(status.textContent).toBe("1 result"));++ search(dialog, "s");+ const count = within(dialog).getAllByRole("option").length;+ await waitFor(() => expect(status.textContent).toBe(`${count} results`));+ });++ it("switches to another site on the same section", async () => {+ mocks.pathname = "/12/sessions";+ render(<CommandPalette />);+ const dialog = await openPalette();++ const input = search(dialog, "docs");+ await waitFor(() => expect(within(dialog).getAllByRole("option")[0].getAttribute("aria-selected")).toBe("true"));+ fireEvent.keyDown(input, { key: "Enter" });++ expect(mocks.push).toHaveBeenCalledWith("/13/sessions");+ });++ it("applies a date preset like its hotkey, only on pages with a date selector", async () => {+ render(<CommandPalette />);+ let dialog = await openPalette();++ const input = search(dialog, "last 7");+ expect(optionNames(dialog)[0]).toBe("Last 7 Days, Date range");+ await waitFor(() => expect(within(dialog).getAllByRole("option")[0].getAttribute("aria-selected")).toBe("true"));+ fireEvent.keyDown(input, { key: "Enter" });++ expect(useStore.getState().time.wellKnown).toBe("last-7-days");+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ cleanup();++ mocks.pathname = "/12/retention";+ render(<CommandPalette />);+ dialog = await openPalette();+ expect(within(dialog).queryByText("Date range")).toBeNull();+ expect(optionNames(dialog).some(name => name?.endsWith("Date range"))).toBe(false);+ });++ it("hands over to the shortcut sheet from its command", async () => {+ render(<CommandPalette />);+ const dialog = await openPalette();++ const input = search(dialog, "keyboard");+ await waitFor(() => expect(within(dialog).getAllByRole("option")[0].getAttribute("aria-selected")).toBe("true"));+ fireEvent.keyDown(input, { key: "Enter" });++ expect(await screen.findByRole("dialog", { name: "Keyboard shortcuts" })).toBeTruthy();+ await waitFor(() => expect(screen.queryByRole("dialog", { name: "Command palette" })).toBeNull());+ });++ it("opens the shortcut sheet with ? unless the user is typing", async () => {+ render(+ <>+ <input aria-label="Filter" />+ <CommandPalette />+ </>+ );+ const field = screen.getByRole("textbox", { name: "Filter" });+ field.focus();+ fireEvent.keyDown(field, { key: "?", code: "Slash", shiftKey: true });+ expect(screen.queryByRole("dialog")).toBeNull();++ fireEvent.keyDown(document.body, { key: "?", code: "Slash", shiftKey: true });+ const sheet = await screen.findByRole("dialog", { name: "Keyboard shortcuts" });++ const row = (label: string) => within(sheet).getByText(label).parentElement?.textContent;+ expect(row("Open command palette")).toBe("Open command palette" + "CtrlK");+ expect(row("Today")).toBe("TodayD");+ expect(row("Last 30 Minutes")).toBe("Last 30 MinutesR");+ expect(row("Custom range")).toBe("Custom rangeC");+ expect(row("Back 10 seconds")).toBe("Back 10 seconds←");+ expect(row("Save changes")).toBe("Save changesCtrlS");++ // "?" again closes it.+ fireEvent.keyDown(sheet, { key: "?", code: "Slash", shiftKey: true });+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ });++ it("keeps page shortcuts and Escape from acting on the page behind an overlay", async () => {+ const pageShortcut = vi.fn();+ const windowShortcut = vi.fn();+ document.addEventListener("keydown", pageShortcut);+ window.addEventListener("keydown", windowShortcut);+ render(<CommandPalette />);++ fireEvent.keyDown(document.body, { key: "?", code: "Slash", shiftKey: true });+ const sheet = await screen.findByRole("dialog", { name: "Keyboard shortcuts" });+ pageShortcut.mockClear();+ windowShortcut.mockClear();++ fireEvent.keyDown(sheet, { key: "d", code: "KeyD" });+ fireEvent.keyDown(sheet, { key: "ArrowLeft", code: "ArrowLeft" });+ fireEvent.keyDown(sheet, { key: "Escape", code: "Escape" });++ expect(pageShortcut).not.toHaveBeenCalled();+ expect(windowShortcut).not.toHaveBeenCalled();+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());++ document.removeEventListener("keydown", pageShortcut);+ window.removeEventListener("keydown", windowShortcut);+ });++ it("stays off for signed-out visitors, private links and embeds", async () => {+ mocks.signedIn = false;+ render(<CommandPalette />);+ pressCtrlK();+ fireEvent.keyDown(document.body, { key: "?", shiftKey: true });+ expect(screen.queryByRole("dialog")).toBeNull();+ cleanup();++ mocks.signedIn = true;+ mocks.pathname = "/12/abcdef123456/main";+ render(<CommandPalette />);+ pressCtrlK();+ expect(screen.queryByRole("dialog")).toBeNull();+ cleanup();++ mocks.pathname = "/12/main";+ window.history.replaceState(null, "", "/12/main?embed=true");+ render(<CommandPalette />);+ pressCtrlK();+ expect(screen.queryByRole("dialog")).toBeNull();+ });+});++describe("CommandPaletteTrigger", () => {+ it("opens the palette and shows its shortcut", async () => {+ render(+ <>+ <CommandPaletteTrigger />+ <CommandPalette />+ </>+ );+ const trigger = screen.getByRole("button", { name: /Search/ });+ expect(trigger.getAttribute("aria-keyshortcuts")).toBe("Control+K");+ expect(trigger.textContent).toBe("SearchCtrlK");++ fireEvent.click(trigger);++ expect(await screen.findByRole("dialog", { name: "Command palette" })).toBeTruthy();+ });++ it("renders nothing for signed-out visitors", () => {+ mocks.signedIn = false;+ render(<CommandPaletteTrigger />);+ expect(screen.queryByRole("button")).toBeNull();+ });+});diff --git a/client/src/components/command-palette/CommandPalette.tsx b/client/src/components/command-palette/CommandPalette.tsxnew file mode 100644index 000000000..7d29215dc--- /dev/null+++ b/client/src/components/command-palette/CommandPalette.tsx@@ -0,0 +1,339 @@+// Adapted from interior.dev "Command Palette" (MIT). See ../interior/THIRD_PARTY_LICENSES.md+"use client";++import { Command as CommandPrimitive } from "cmdk";+import { motion } from "framer-motion";+import { Check } from "lucide-react";+import { useExtracted } from "next-intl";+import { usePathname } from "next/navigation";+import { useEffect, useLayoutEffect, useRef, useState, type PointerEvent } from "react";+import { Command, CommandDialog, CommandInput, CommandList } from "@/components/ui/command";+import { FADE_IN, SPRING_CELL } from "@/lib/motion";+import { paletteEntries, type PaletteEntry } from "./entries";+import {+ isApplePlatform,+ isEditableTarget,+ isEmbedView,+ isPaletteShortcut,+ isShortcutSheetKey,+ keepEscapeInOverlay,+ keepKeysInOverlay,+} from "./keys";+import { KeyCaps } from "./KeyCaps";+import { getActiveSiteId } from "./routes";+import { ShortcutSheet } from "./ShortcutSheet";+import { closeOverlay, restoreFocus, showOverlay, usePaletteOverlay } from "./store";+import { useCommandPaletteAvailable } from "./useCommandPaletteAvailable";+import { GROUP_LIMITS, usePaletteCommands, useSiteEntityCommands, type PaletteCommand } from "./usePaletteCommands";++// A search renders at most this many rows; the rest are a few keystrokes away.+const MAX_RESULTS = 50;+const ENTRY_OPTIONS = { groupLimits: GROUP_LIMITS, maxResults: MAX_RESULTS };+const NO_COMMANDS: PaletteCommand[] = [];+const NO_ENTRIES: ReadonlySet<string> = new Set();++const entryKey = (entry: PaletteEntry<PaletteCommand>) =>+ entry.kind === "row" ? entry.item.id : `heading:${entry.group}`;++/** Entries drawn inside the list's visible area, by entry key. */+function entriesOnScreen(list: HTMLElement | null): Set<string> {+ const onScreen = new Set<string>();+ if (!list) return onScreen;++ const { top, bottom } = list.getBoundingClientRect();+ list.querySelectorAll<HTMLElement>("[data-entry]").forEach(element => {+ const rect = element.getBoundingClientRect();+ if (rect.bottom > top && rect.top < bottom && element.dataset.entry) onScreen.add(element.dataset.entry);+ });+ return onScreen;+}++/**+ * ⌘K (Ctrl+K off Apple platforms) toggles the command palette from anywhere,+ * including text fields. "?" opens the keyboard shortcut sheet unless the user+ * is typing. Mounted once for the whole app; renders nothing for visitors.+ */+export function CommandPalette() {+ const available = useCommandPaletteAvailable();+ const overlay = usePaletteOverlay(state => state.overlay);++ useEffect(() => {+ if (!available) {+ closeOverlay();+ return;+ }++ const apple = isApplePlatform();+ const onKeyDown = (event: KeyboardEvent) => {+ // A focused editor that claims the chord (defaultPrevented) keeps it.+ if (event.defaultPrevented || event.repeat || event.isComposing || isEmbedView()) return;+ const current = usePaletteOverlay.getState().overlay;++ if (isPaletteShortcut(event, apple)) {+ event.preventDefault();+ if (current === "palette") closeOverlay();+ else showOverlay("palette");+ } else if (current === null && isShortcutSheetKey(event) && !isEditableTarget(event.target)) {+ event.preventDefault();+ showOverlay("shortcuts");+ }+ };++ document.addEventListener("keydown", onKeyDown);+ return () => document.removeEventListener("keydown", onKeyDown);+ }, [available]);++ if (!available) return null;++ return (+ <>+ <PaletteDialog open={overlay === "palette"} />+ <ShortcutSheet open={overlay === "shortcuts"} />+ </>+ );+}++function PaletteDialog({ open }: { open: boolean }) {+ const t = useExtracted();++ return (+ <CommandDialog+ open={open}+ onOpenChange={next => (next ? showOverlay("palette") : closeOverlay())}+ title={t("Command palette")}+ description={t("Search for a page, site or action, then press Enter to run it.")}+ onCloseAutoFocus={restoreFocus}+ onEscapeKeyDown={keepEscapeInOverlay}+ onKeyDown={keepKeysInOverlay}+ >+ <PaletteContent />+ </CommandDialog>+ );+}++function PaletteContent() {+ const siteId = getActiveSiteId(usePathname());+ return siteId === null ? <PaletteView entityCommands={NO_COMMANDS} /> : <SitePaletteView siteId={siteId} />;+}++function SitePaletteView({ siteId }: { siteId: number }) {+ const entityCommands = useSiteEntityCommands(siteId);+ return <PaletteView entityCommands={entityCommands} />;+}++function PaletteView({ entityCommands }: { entityCommands: PaletteCommand[] }) {+ const t = useExtracted();+ const { commands, groupLabels } = usePaletteCommands(entityCommands);+ const [query, setQuery] = useState("");+ // The selected row. Controlled so a pointer only selects when it really moves.+ const [value, setValue] = useState("");+ // React keys by entry key. An entry keeps its key while it stays on screen,+ // so a re-rank glides it from where it was drawn. One that was off screen+ // (below the fold, or not listed) gets a fresh key and mounts in its final+ // slot rather than flying in from a position nobody could see.+ const [keys, setKeys] = useState<Record<string, string>>({});+ // Entries mounted by the latest query change; they fade in where they land.+ const [arriving, setArriving] = useState<ReadonlySet<string>>(NO_ENTRIES);+ const queryChanges = useRef(0);+ const listRef = useRef<HTMLDivElement>(null);+ const liveRef = useRef<HTMLSpanElement>(null);+ const pointer = useRef({ x: -1, y: -1 });++ const searching = query.trim() !== "";+ const { entries, total } = paletteEntries(commands, query, ENTRY_OPTIONS);++ const changeQuery = (next: string) => {+ const onScreen = entriesOnScreen(listRef.current);+ const change = ++queryChanges.current;+ const incoming = new Set(+ paletteEntries(commands, next, ENTRY_OPTIONS)+ .entries.map(entryKey)+ .filter(key => !onScreen.has(key))+ );+ setKeys(current => {+ const updated = { ...current };+ incoming.forEach(key => {+ updated[key] = `${key}~${change}`;+ });+ return updated;+ });+ setArriving(incoming);+ setQuery(next);+ };++ // Back to the top once the rows re-rank. This runs after framer has recorded+ // where each row was drawn and before it measures where the row went, so a+ // glide always starts from what the user saw, scrolled or not.+ useLayoutEffect(() => {+ if (listRef.current) listRef.current.scrollTop = 0;+ }, [query]);++ const announcement = !searching+ ? ""+ : total === 0+ ? t("No results")+ : t("{count, plural, one {# result} other {# results}}", { count: total });++ // The combobox announces the active row; the result count follows once typing+ // settles. Keyed on the text, so moving through rows does not repeat it.+ useEffect(() => {+ const live = liveRef.current;+ if (!live) return;+ if (!announcement) {+ live.textContent = "";+ return;+ }+ const id = setTimeout(() => {+ live.textContent = announcement;+ }, 400);+ return () => clearTimeout(id);+ }, [announcement]);++ const run = (command: PaletteCommand) => {+ command.run();+ // A command that opened the shortcut sheet has already replaced the palette.+ if (usePaletteOverlay.getState().overlay === "palette") closeOverlay();+ };++ // Rows glide under a resting pointer; only an actual move may take the selection.+ const selectFromPointer = (id: string, event: PointerEvent) => {+ const { x, y } = pointer.current;+ if (event.clientX === x && event.clientY === y) return;+ pointer.current = { x: event.clientX, y: event.clientY };+ if (id !== value) setValue(id);+ };++ return (+ <Command+ label={t("Search commands")}+ shouldFilter={false}+ disablePointerSelection+ vimBindings={false}+ loop+ value={value}+ onValueChange={setValue}+ >+ <CommandInput+ value={query}+ onValueChange={changeQuery}+ placeholder={t("Search or jump to…")}+ wrapperClassName="h-12 px-4 border-neutral-150 dark:border-neutral-750"+ className="h-12"+ >+ <KeyCaps aria-hidden keys={[t("Esc")]} />+ </CommandInput>+ <CommandList+ ref={listRef}+ label={t("Commands")}+ // Clicking a row or the gutter keeps focus, and typing, in the search field.+ onMouseDown={event => event.preventDefault()}+ className="relative h-[min(22rem,60dvh)] max-h-none scroll-pb-1.5 scroll-pt-9 overscroll-contain p-1.5"+ >+ {entries.map(entry => {+ const key = entryKey(entry);+ const fadeIn = arriving.has(key);++ return entry.kind === "heading" ? (+ <motion.div+ key={keys[key] ?? key}+ data-entry={key}+ aria-hidden+ initial={fadeIn ? { opacity: 0 } : false}+ animate={{ opacity: 1 }}+ transition={FADE_IN}+ className="truncate px-2.5 pb-1.5 pt-3 text-xs font-medium text-neutral-600 first:pt-1.5 dark:text-neutral-400"+ >+ {groupLabels[entry.group]}+ </motion.div>+ ) : (+ <PaletteRow+ key={keys[key] ?? key}+ command={entry.item}+ groupLabel={groupLabels[entry.item.group]}+ searching={searching}+ query={query}+ fadeIn={fadeIn}+ onRun={run}+ onPointerSelect={selectFromPointer}+ />+ );+ })}+ {entries.length === 0 && (+ <p+ aria-hidden+ className="absolute inset-0 flex items-center justify-center px-4 text-center text-sm text-neutral-600 dark:text-neutral-400"+ >+ {t("No results")}+ </p>+ )}+ </CommandList>+ <span ref={liveRef} role="status" aria-live="polite" className="sr-only" />+ </Command>+ );+}++function PaletteRow({+ command,+ groupLabel,+ searching,+ query,+ fadeIn,+ onRun,+ onPointerSelect,+}: {+ command: PaletteCommand;+ groupLabel: string;+ searching: boolean;+ query: string;+ /** Mounted by a query change: fade in at the final slot. */+ fadeIn: boolean;+ onRun: (command: PaletteCommand) => void;+ onPointerSelect: (id: string, event: PointerEvent) => void;+}) {+ const t = useExtracted();+ // Headings are visual only, so every option names its group itself.+ const accessibleName = [command.label, command.hint, groupLabel, command.current ? t("Current") : undefined]+ .filter(Boolean)+ .join(", ");++ return (+ <CommandPrimitive.Item asChild value={command.id} onSelect={() => onRun(command)}>+ <motion.div+ aria-label={accessibleName}+ data-entry={command.id}+ // A row that stays on screen travels to its new rank as the query+ // changes. Only a query change moves it: rows that shift because a+ // list finished loading jump, since the user did not cause that.+ layout="position"+ layoutDependency={query}+ initial={fadeIn ? { opacity: 0 } : false}+ animate={{ opacity: 1 }}+ // New rows wait for the gliding ones to clear their slot, so text never overlaps.+ transition={{ layout: SPRING_CELL, opacity: fadeIn ? { ...FADE_IN, delay: 0.1 } : FADE_IN }}+ onPointerMove={event => onPointerSelect(command.id, event)}+ className="flex h-9 cursor-pointer select-none items-center gap-2.5 rounded-md px-2.5 text-sm text-neutral-800 outline-none data-[selected=true]:bg-neutral-100 dark:text-neutral-100 dark:data-[selected=true]:bg-neutral-750"+ >+ <span+ aria-hidden+ className="flex h-4 w-4 shrink-0 items-center justify-center text-neutral-500 dark:text-neutral-400 [&_svg]:h-4 [&_svg]:w-4"+ >+ {command.icon}+ </span>+ <span className="min-w-0 truncate">{command.label}</span>+ {command.hint && (+ <span className="min-w-0 shrink-[3] truncate text-xs text-neutral-600 dark:text-neutral-400">+ {command.hint}+ </span>+ )}+ <span className="ml-auto flex shrink-0 items-center gap-2 pl-2">+ {/* Headings name the groups until the list is ranked; then each row shows its own. */}+ {searching && (+ <span className="max-w-40 truncate text-xs text-neutral-600 dark:text-neutral-400">{groupLabel}</span>+ )}+ {command.current && <Check aria-hidden className="h-4 w-4 text-emerald-600 dark:text-emerald-400" />}+ {command.shortcut && <KeyCaps keys={command.shortcut} />}+ </span>+ </motion.div>+ </CommandPrimitive.Item>+ );+}diff --git a/client/src/components/command-palette/CommandPaletteTrigger.tsx b/client/src/components/command-palette/CommandPaletteTrigger.tsxnew file mode 100644index 000000000..3f8001fdf--- /dev/null+++ b/client/src/components/command-palette/CommandPaletteTrigger.tsx@@ -0,0 +1,34 @@+"use client";++import { Search } from "lucide-react";+import { useExtracted } from "next-intl";+import { cn } from "@/lib/utils";+import { useApplePlatform } from "./keys";+import { KeyCaps } from "./KeyCaps";+import { openCommandPalette } from "./store";+import { useCommandPaletteAvailable } from "./useCommandPaletteAvailable";++/** A visible way into the palette, with its shortcut, for people who don't know ⌘K yet. */+export function CommandPaletteTrigger({ className }: { className?: string }) {+ const t = useExtracted();+ const available = useCommandPaletteAvailable();+ const apple = useApplePlatform();++ if (!available) return null;++ return (+ <button+ type="button"+ onClick={openCommandPalette}+ aria-keyshortcuts={apple === false ? "Control+K" : "Meta+K"}+ className={cn(+ "flex h-8 w-full items-center gap-2 rounded-lg border border-neutral-200 px-2.5 text-sm text-neutral-600 transition-colors hover:bg-neutral-150 hover:text-neutral-900 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-950 dark:border-neutral-800 dark:text-neutral-400 dark:hover:bg-neutral-800/50 dark:hover:text-white dark:focus-visible:ring-neutral-300",+ className+ )}+ >+ <Search aria-hidden className="h-4 w-4 shrink-0" />+ <span className="flex-1 text-left">{t("Search")}</span>+ {apple !== null && <KeyCaps aria-hidden keys={[apple ? "⌘" : t("Ctrl"), "K"]} />}+ </button>+ );+}diff --git a/client/src/components/command-palette/KeyCaps.tsx b/client/src/components/command-palette/KeyCaps.tsxnew file mode 100644index 000000000..b745d9548--- /dev/null+++ b/client/src/components/command-palette/KeyCaps.tsx@@ -0,0 +1,23 @@+import type { HTMLAttributes } from "react";+import { cn } from "@/lib/utils";++/** Neutral key caps for a shortcut, e.g. ["⌘", "K"]. */+export function KeyCaps({+ keys,+ className,+ ...props+}: { keys: readonly string[] } & Omit<HTMLAttributes<HTMLSpanElement>, "children">) {+ return (+ <span className={cn("flex shrink-0 items-center gap-1", className)} {...props}>+ {keys.map((key, index) => (+ <kbd+ key={index}+ // Preflight sets kbd in the mono stack; key caps stay in Inter like the rest of the UI.+ className="inline-flex h-5 min-w-5 items-center justify-center rounded-md border border-neutral-200 px-1 font-[family-name:inherit] text-[11px] font-medium leading-none text-neutral-600 dark:border-neutral-700 dark:text-neutral-400"+ >+ {key}+ </kbd>+ ))}+ </span>+ );+}diff --git a/client/src/components/command-palette/ShortcutSheet.tsx b/client/src/components/command-palette/ShortcutSheet.tsxnew file mode 100644index 000000000..08a6db52b--- /dev/null+++ b/client/src/components/command-palette/ShortcutSheet.tsx@@ -0,0 +1,96 @@+"use client";++import { useExtracted } from "next-intl";+import {+ CUSTOM_RANGE_HOTKEY,+ HOTKEY_FOR_PRESET,+ PRESET_GROUPS,+ usePresetLabels,+} from "@/components/DateSelector/presets";+import { SKIP_SECONDS } from "@/components/replay/player/utils/replayUtils";+import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { isShortcutSheetKey, keepEscapeInOverlay, keepKeysInOverlay, useApplePlatform } from "./keys";+import { KeyCaps } from "./KeyCaps";+import { closeOverlay, restoreFocus, showOverlay } from "./store";++type Shortcut = { label: string; keys: string[] };++/** The "?" sheet: every keyboard shortcut in the app, read from the same constants the handlers use. */+export function ShortcutSheet({ open }: { open: boolean }) {+ const t = useExtracted();+ const presetLabels = usePresetLabels();+ const apple = useApplePlatform();+ const mod = apple === false ? t("Ctrl") : "⌘";+ const skipSeconds = String(SKIP_SECONDS / 1000);++ const general: Shortcut[] = [+ { label: t("Open command palette"), keys: [mod, "K"] },+ { label: t("Show keyboard shortcuts"), keys: ["?"] },+ ];+ const replay: Shortcut[] = [+ { label: t("Back {seconds} seconds", { seconds: skipSeconds }), keys: ["←"] },+ { label: t("Forward {seconds} seconds", { seconds: skipSeconds }), keys: ["→"] },+ { label: t("Play or pause"), keys: [t("Space")] },+ ];+ const dashboard: Shortcut[] = [+ { label: t("Save changes"), keys: [mod, "S"] },+ { label: t("Cancel editing"), keys: [t("Esc")] },+ ];+ // In menu order rather than key order, so the list reads like the date selector.+ const dateRange: Shortcut[] = [+ ...PRESET_GROUPS.flatMap(group => group.presets).flatMap(preset => {+ const hotkey = HOTKEY_FOR_PRESET[preset];+ return hotkey ? [{ label: presetLabels[preset], keys: [hotkey.toUpperCase()] }] : [];+ }),+ { label: t("Custom range"), keys: [CUSTOM_RANGE_HOTKEY.toUpperCase()] },+ ];++ return (+ <Dialog open={open} onOpenChange={next => (next ? showOverlay("shortcuts") : closeOverlay())}>+ <DialogContent+ aria-describedby={undefined}+ className="max-h-[85dvh] max-w-2xl overflow-y-auto"+ onCloseAutoFocus={restoreFocus}+ onEscapeKeyDown={keepEscapeInOverlay}+ onKeyDown={event => {+ // "?" again closes the sheet.+ if (isShortcutSheetKey(event)) {+ event.preventDefault();+ closeOverlay();+ }+ keepKeysInOverlay(event);+ }}+ >+ <DialogHeader>+ <DialogTitle>{t("Keyboard shortcuts")}</DialogTitle>+ </DialogHeader>+ <div className="grid gap-x-10 gap-y-6 sm:grid-cols-2">+ <div className="space-y-6">+ <ShortcutSection title={t("General")} shortcuts={general} />+ <ShortcutSection title={t("Session replay")} shortcuts={replay} />+ <ShortcutSection title={t("Dashboard editing")} shortcuts={dashboard} />+ </div>+ <ShortcutSection title={t("Date range")} shortcuts={dateRange} />+ </div>+ </DialogContent>+ </Dialog>+ );+}++function ShortcutSection({ title, shortcuts }: { title: string; shortcuts: Shortcut[] }) {+ return (+ <section>+ <h3 className="mb-1 text-xs font-medium text-neutral-600 dark:text-neutral-400">{title}</h3>+ <dl className="divide-y divide-neutral-100 dark:divide-neutral-850">+ {shortcuts.map(shortcut => (+ <div key={shortcut.label} className="flex items-center justify-between gap-4 py-1.5">+ <dt className="text-sm text-neutral-800 dark:text-neutral-200">{shortcut.label}</dt>+ <dd>+ <KeyCaps keys={shortcut.keys} />+ </dd>+ </div>+ ))}+ </dl>+ </section>+ );+}diff --git a/client/src/components/command-palette/entries.test.ts b/client/src/components/command-palette/entries.test.tsnew file mode 100644index 000000000..d57c75c87--- /dev/null+++ b/client/src/components/command-palette/entries.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from "vitest";+import { paletteEntries, type PaletteEntry } from "./entries";++type Item = { id: string; label: string; group: "site" | "sites" | "theme" };++const item = (group: Item["group"], label: string): Item => ({ id: `${group}:${label}`, label, group });++const ITEMS: Item[] = [+ item("site", "Main"),+ item("site", "Sessions"),+ item("sites", "docs.rybbit.com"),+ item("sites", "shop.example"),+ item("sites", "blog.example"),+ item("theme", "Dark"),+];++const describeEntries = (entries: PaletteEntry<Item>[]) =>+ entries.map(entry => (entry.kind === "heading" ? `# ${entry.group}` : entry.item.label));++describe("paletteEntries", () => {+ it("lists every row under a heading per group when there is no query", () => {+ const { entries, total } = paletteEntries(ITEMS, "");+ expect(describeEntries(entries)).toEqual([+ "# site",+ "Main",+ "Sessions",+ "# sites",+ "docs.rybbit.com",+ "shop.example",+ "blog.example",+ "# theme",+ "Dark",+ ]);+ expect(total).toBe(6);+ });++ it("caps a group before the user types", () => {+ const { entries } = paletteEntries(ITEMS, "", { groupLimits: { sites: 2 } });+ expect(describeEntries(entries)).toEqual([+ "# site",+ "Main",+ "Sessions",+ "# sites",+ "docs.rybbit.com",+ "shop.example",+ "# theme",+ "Dark",+ ]);+ });++ it("drops the heading of a group that shows no rows", () => {+ const { entries } = paletteEntries(ITEMS, "", { groupLimits: { theme: 0 } });+ expect(describeEntries(entries)).not.toContain("# theme");+ });++ it("ranks one flat list across groups, ignoring group caps, once there is a query", () => {+ const { entries, total } = paletteEntries(ITEMS, "s", { groupLimits: { sites: 1 } });+ expect(entries.every(entry => entry.kind === "row")).toBe(true);+ expect(describeEntries(entries)).toEqual(["Sessions", "shop.example", "docs.rybbit.com"]);+ expect(total).toBe(3);+ });++ it("renders at most maxResults rows but counts every match", () => {+ const { entries, total } = paletteEntries(ITEMS, "s", { maxResults: 2 });+ expect(describeEntries(entries)).toEqual(["Sessions", "shop.example"]);+ expect(total).toBe(3);+ });+});diff --git a/client/src/components/command-palette/entries.ts b/client/src/components/command-palette/entries.tsnew file mode 100644index 000000000..1119fb725--- /dev/null+++ b/client/src/components/command-palette/entries.ts@@ -0,0 +1,46 @@+import { rank, type RankItem } from "./rank";++type GroupedItem = RankItem & { group: string };++export type PaletteEntry<T extends GroupedItem> = { kind: "heading"; group: T["group"] } | { kind: "row"; item: T };++type Options<G extends string> = {+ /** Most rows a group shows before the user types. Typing searches every row. */+ groupLimits?: Partial<Record<G, number>>;+ /** Most rows a search renders. */+ maxResults?: number;+};++/**+ * What the palette lists for `query`. With no query, the rows keep their+ * registry order under a heading per group; `items` must already be ordered+ * group by group. With a query, one flat list ranked best first. `total`+ * counts every match, including rows past `maxResults`.+ */+export function paletteEntries<T extends GroupedItem>(+ items: readonly T[],+ query: string,+ { groupLimits = {}, maxResults = Infinity }: Options<T["group"]> = {}+): { entries: PaletteEntry<T>[]; total: number } {+ if (query.trim()) {+ const ranked = rank(items, query);+ return {+ entries: ranked.slice(0, maxResults).map(item => ({ kind: "row", item })),+ total: ranked.length,+ };+ }++ const limits: Partial<Record<string, number>> = groupLimits;+ const entries: PaletteEntry<T>[] = [];+ const shown = new Map<string, number>();++ for (const item of items) {+ const count = shown.get(item.group) ?? 0;+ if (count >= (limits[item.group] ?? Infinity)) continue;+ if (count === 0) entries.push({ kind: "heading", group: item.group });+ entries.push({ kind: "row", item });+ shown.set(item.group, count + 1);+ }++ return { entries, total: items.length };+}diff --git a/client/src/components/command-palette/keys.test.ts b/client/src/components/command-palette/keys.test.tsnew file mode 100644index 000000000..71562081a--- /dev/null+++ b/client/src/components/command-palette/keys.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from "vitest";+import { isPaletteShortcut, isShortcutSheetKey } from "./keys";++const key = (init: Partial<KeyboardEvent>) =>+ ({ key: "", code: "", metaKey: false, ctrlKey: false, altKey: false, shiftKey: false, ...init }) as KeyboardEvent;++describe("isPaletteShortcut", () => {+ it("is ⌘K on Apple platforms", () => {+ expect(isPaletteShortcut(key({ key: "k", code: "KeyK", metaKey: true }), true)).toBe(true);+ expect(isPaletteShortcut(key({ key: "k", code: "KeyK", ctrlKey: true }), true)).toBe(false);+ });++ it("is Ctrl+K elsewhere", () => {+ expect(isPaletteShortcut(key({ key: "k", code: "KeyK", ctrlKey: true }), false)).toBe(true);+ expect(isPaletteShortcut(key({ key: "k", code: "KeyK", metaKey: true }), false)).toBe(false);+ });++ it("ignores K alone and K with extra modifiers", () => {+ expect(isPaletteShortcut(key({ key: "k", code: "KeyK" }), true)).toBe(false);+ expect(isPaletteShortcut(key({ key: "K", code: "KeyK", metaKey: true, shiftKey: true }), true)).toBe(false);+ expect(isPaletteShortcut(key({ key: "˚", code: "KeyK", metaKey: true, altKey: true }), true)).toBe(false);+ expect(isPaletteShortcut(key({ key: "k", code: "KeyK", metaKey: true, ctrlKey: true }), true)).toBe(false);+ });++ it("accepts caps lock", () => {+ expect(isPaletteShortcut(key({ key: "K", code: "KeyK", metaKey: true }), true)).toBe(true);+ });++ it("follows the layout's letter, falling back to the physical key on non-Latin layouts", () => {+ // Russian: the K key types л.+ expect(isPaletteShortcut(key({ key: "л", code: "KeyK", ctrlKey: true }), false)).toBe(true);+ // Dvorak: the K key types t, and k lives on the V key.+ expect(isPaletteShortcut(key({ key: "t", code: "KeyK", ctrlKey: true }), false)).toBe(false);+ expect(isPaletteShortcut(key({ key: "k", code: "KeyV", ctrlKey: true }), false)).toBe(true);+ });++ it("ignores keydown events without a key, as autofill sends", () => {+ expect(isPaletteShortcut(key({ key: undefined, metaKey: true }), true)).toBe(false);+ });+});++describe("isShortcutSheetKey", () => {+ it("is a plain question mark", () => {+ expect(isShortcutSheetKey(key({ key: "?", code: "Slash", shiftKey: true }))).toBe(true);+ expect(isShortcutSheetKey(key({ key: "/", code: "Slash" }))).toBe(false);+ });++ it("leaves chords with ?, like the macOS Help menu, alone", () => {+ expect(isShortcutSheetKey(key({ key: "?", shiftKey: true, metaKey: true }))).toBe(false);+ expect(isShortcutSheetKey(key({ key: "?", shiftKey: true, ctrlKey: true }))).toBe(false);+ });+});diff --git a/client/src/components/command-palette/keys.ts b/client/src/components/command-palette/keys.tsnew file mode 100644index 000000000..a9c8c6013--- /dev/null+++ b/client/src/components/command-palette/keys.ts@@ -0,0 +1,62 @@+import { useSyncExternalStore, type KeyboardEvent as ReactKeyboardEvent } from "react";++type KeyInput = Pick<KeyboardEvent, "key" | "code" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey">;++export const isApplePlatform = () => /mac|iphone|ipad|ipod/i.test(navigator.platform || navigator.userAgent);++// The platform never changes, so there is nothing to subscribe to. The server+// snapshot is null: key hints render after hydration instead of guessing.+const subscribeToNothing = () => () => {};+const getServerPlatform = () => null;++/** True on Apple platforms (⌘), false elsewhere (Ctrl), null until hydrated. */+export function useApplePlatform(): boolean | null {+ return useSyncExternalStore<boolean | null>(subscribeToNothing, isApplePlatform, getServerPlatform);+}++/** ⌘K on Apple platforms, Ctrl+K elsewhere. */+export function isPaletteShortcut(event: KeyInput, apple: boolean): boolean {+ // Autofill fires keydown events without a key.+ if (typeof event.key !== "string" || event.altKey || event.shiftKey) return false;+ const modifier = apple ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey;+ if (!modifier) return false;++ const key = event.key.toLowerCase();+ // Non-Latin layouts report their own letter as the key; fall back to the physical K there.+ return key === "k" || (!/^[a-z]$/.test(key) && event.code === "KeyK");+}++/** "?" (Shift+/ on US layouts, wherever the layout puts it otherwise). */+export function isShortcutSheetKey(event: KeyInput): boolean {+ return event.key === "?" && !event.metaKey && !event.ctrlKey && !event.altKey;+}++/** Same rule as the date preset hotkeys: typing into a field is never a shortcut. */+export function isEditableTarget(target: EventTarget | null): boolean {+ if (!(target instanceof HTMLElement)) return false;+ if (target.isContentEditable) return true;+ const tag = target.tagName;+ return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT";+}++/** Embedded dashboards (iframes on other sites) get no global shortcuts. */+export const isEmbedView = () => new URLSearchParams(window.location.search).get("embed") === "true";++/**+ * Page shortcuts (date presets, replay seeking) listen on document and window.+ * React sees a key before those listeners do, so an open overlay stops plain+ * keys here and the page behind it stays put. Chords such as ⌘K still pass.+ */+export function keepKeysInOverlay(event: ReactKeyboardEvent) {+ if (event.metaKey || event.ctrlKey || event.altKey) return;+ event.nativeEvent.stopImmediatePropagation();+}++/**+ * Radix closes the overlay on Escape from a capture listener on document.+ * Stopping the event there keeps it from also reaching the dashboard editor's+ * Escape-to-cancel listener on window.+ */+export function keepEscapeInOverlay(event: KeyboardEvent) {+ event.stopPropagation();+}diff --git a/client/src/components/command-palette/rank.test.ts b/client/src/components/command-palette/rank.test.tsnew file mode 100644index 000000000..0b6ec7843--- /dev/null+++ b/client/src/components/command-palette/rank.test.ts@@ -0,0 +1,84 @@+import { describe, expect, it } from "vitest";+import { fold, rank, scoreOne } from "./rank";++const labels = (items: { label: string }[]) => items.map(item => item.label);+const items = (...names: string[]) => names.map(label => ({ label }));++describe("scoreOne", () => {+ it("returns -1 when the query is not an in-order subsequence", () => {+ expect(scoreOne("Sessions", "xyz")).toBe(-1);+ expect(scoreOne("Sessions", "sne")).toBe(-1);+ });++ it("rewards a match at the very start and consecutive characters", () => {+ // s (start: 2 + 12), e (run of 1: 2 + 4), s (run of 2: 2 + 8)+ expect(scoreOne("Sessions", "ses")).toBe(30);+ // s mid-word (2), e right after (2 + 4), s after a gap (2)+ expect(scoreOne("Users", "ses")).toBe(10);+ });++ it("scores a run above the same letters scattered mid-word", () => {+ expect(scoreOne("sets", "set")).toBeGreaterThan(scoreOne("sxext", "set"));+ });++ it("rewards letters that start words, so initials find a label", () => {+ // l (start: 2 + 12), w after a space (2 + 8)+ expect(scoreOne("Last Week", "lw")).toBe(24);+ expect(scoreOne("Yellow", "lw")).toBe(4);+ });+});++describe("fold", () => {+ it("lower-cases and drops accents", () => {+ expect(fold("Übersicht Événements")).toBe("ubersicht evenements");+ });+});++describe("rank", () => {+ it("returns every item in its original order for an empty or blank query", () => {+ const list = items("Main", "Globe", "Sessions");+ expect(rank(list, "")).toEqual(list);+ expect(rank(list, " ")).toEqual(list);+ expect(rank(list, "")).not.toBe(list);+ });++ it("drops items that do not match", () => {+ expect(labels(rank(items("Main", "Globe"), "xyz"))).toEqual([]);+ });++ it("puts the strongest match first", () => {+ expect(labels(rank(items("Users", "Events", "Sessions"), "ses"))).toEqual(["Sessions", "Users"]);+ });++ it("is case-insensitive, accent-insensitive and trims the query", () => {+ expect(labels(rank(items("Globe", "Übersicht"), " UBER "))).toEqual(["Übersicht"]);+ });++ it("matches keywords, a little below the same match in a label", () => {+ const list = [{ label: "Cohorts", keywords: "retention" }, { label: "Retention" }];+ expect(labels(rank(list, "ret"))).toEqual(["Retention", "Cohorts"]);+ });++ it("ignores a single keyword letter in the middle of a word", () => {+ // Upstream behavior: the keyword penalty pushes a lone mid-word hit below zero.+ expect(rank([{ label: "Main", keywords: "overview" }], "v")).toEqual([]);+ expect(labels(rank([{ label: "Main", keywords: "overview" }], "o"))).toEqual(["Main"]);+ });++ it("breaks a tie with the shorter label", () => {+ expect(labels(rank(items("Goals overview", "Goals"), "goa"))).toEqual(["Goals", "Goals overview"]);+ });++ it("keeps the input order for equal scores", () => {+ expect(labels(rank(items("Dusk", "Dark"), "d"))).toEqual(["Dusk", "Dark"]);+ expect(labels(rank(items("Dark", "Dusk"), "d"))).toEqual(["Dark", "Dusk"]);+ });++ it("re-ranks as the query grows", () => {+ const list = items("Sessions", "Settings", "Site settings");+ expect(labels(rank(list, "s"))).toEqual(["Sessions", "Settings", "Site settings"]);+ // The second s starts a word only in "Site settings", which jumps to the top.+ expect(labels(rank(list, "ss"))).toEqual(["Site settings", "Sessions", "Settings"]);+ expect(labels(rank(list, "set"))).toEqual(["Settings", "Site settings"]);+ });+});diff --git a/client/src/components/command-palette/rank.ts b/client/src/components/command-palette/rank.tsnew file mode 100644index 000000000..6ef84a2f5--- /dev/null+++ b/client/src/components/command-palette/rank.ts@@ -0,0 +1,69 @@+// Adapted from interior.dev "Command Palette" (MIT). See ../interior/THIRD_PARTY_LICENSES.md++// A match right after one of these counts as the start of a word.+const BOUNDARY = /[\s\-_/.:]/;+// Combining marks left behind by NFD normalization ("é" → "e" + U+0301).+const DIACRITICS = /[̀-ͯ]/g;++export type RankItem = {+ label: string;+ /** Extra words to match; a hit here scores a little below the same hit in the label. */+ keywords?: string;+};++/**+ * Case- and accent-insensitive form of a label or query, so "ubersicht" finds+ * "Übersicht" in the translated UI.+ */+export function fold(text: string): string {+ return text.normalize("NFD").replace(DIACRITICS, "").toLowerCase();+}++/**+ * Scores `query` (already folded) against `text` as an in-order subsequence.+ * Every query character must appear after the previous one; consecutive runs,+ * a match at the very start and matches at word starts earn more. Returns -1+ * when the text does not contain the query.+ */+export function scoreOne(text: string, query: string): number {+ const folded = fold(text);+ let cursor = 0;+ let total = 0;+ let streak = 0;++ for (let i = 0; i < query.length; i++) {+ const at = folded.indexOf(query[i], cursor);+ if (at < 0) return -1;+ streak = at === cursor && i > 0 ? streak + 1 : 0;+ total += 2 + streak * 4;+ if (at === 0) total += 12;+ else if (BOUNDARY.test(folded[at - 1])) total += 8;+ cursor = at + 1;+ }++ return total;+}++/**+ * The items that match `query`, best first. A label hit beats the same hit in+ * the keywords, a shorter label wins a tie, and equal scores keep their input+ * order. An empty query returns every item in its original order.+ */+export function rank<T extends RankItem>(items: readonly T[], query: string): T[] {+ const q = fold(query.trim());+ if (!q) return [...items];++ const scored: { item: T; score: number; order: number }[] = [];++ for (let i = 0; i < items.length; i++) {+ const item = items[i];+ const direct = scoreOne(item.label, q);+ const aliased = item.keywords ? scoreOne(item.keywords, q) - 3 : -1;+ const best = Math.max(direct, aliased);+ if (best < 0) continue;+ scored.push({ item, score: best - item.label.length * 0.05, order: i });+ }++ scored.sort((a, b) => b.score - a.score || a.order - b.order);+ return scored.map(entry => entry.item);+}diff --git a/client/src/components/command-palette/routes.test.ts b/client/src/components/command-palette/routes.test.tsnew file mode 100644index 000000000..fbca97687--- /dev/null+++ b/client/src/components/command-palette/routes.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from "vitest";+import { getActiveSiteId, getSwitchSitePath, hasDateSelector } from "./routes";++describe("getActiveSiteId", () => {+ it("reads the site from a site route, with or without a private key", () => {+ expect(getActiveSiteId("/12/main")).toBe(12);+ expect(getActiveSiteId("/12/dashboards/4")).toBe(12);+ expect(getActiveSiteId("/12/abcdef123456/main")).toBe(12);+ });++ it("is null outside a site", () => {+ expect(getActiveSiteId("/")).toBeNull();+ expect(getActiveSiteId("/settings/account")).toBeNull();+ expect(getActiveSiteId("/rollup")).toBeNull();+ });+});++describe("hasDateSelector", () => {+ it("is true on pages that mount a DateSelector", () => {+ for (const path of ["/", "/rollup", "/12/main", "/12/sessions", "/12/user/abc", "/12/dashboards/4"]) {+ expect(hasDateSelector(path), path).toBe(true);+ }+ });++ it("is false where the preset hotkeys do nothing", () => {+ for (const path of ["/12/retention", "/12/query", "/12/api-playground", "/12/dashboards", "/settings/account"]) {+ expect(hasDateSelector(path), path).toBe(false);+ }+ });+});++describe("getSwitchSitePath", () => {+ it("keeps the section when switching from a site page", () => {+ expect(getSwitchSitePath("/12/sessions", 13)).toBe("/13/sessions");+ expect(getSwitchSitePath("/12/api-playground", 13)).toBe("/13/api-playground");+ });++ it("drops what belongs to the old site", () => {+ expect(getSwitchSitePath("/12/dashboards/4", 13)).toBe("/13/dashboards");+ expect(getSwitchSitePath("/12/user/abc", 13)).toBe("/13/main");+ });++ it("opens the main page from outside a site", () => {+ expect(getSwitchSitePath("/", 13)).toBe("/13/main");+ expect(getSwitchSitePath("/settings/teams", 13)).toBe("/13/main");+ });+});diff --git a/client/src/components/command-palette/routes.ts b/client/src/components/command-palette/routes.tsnew file mode 100644index 000000000..be15df638--- /dev/null+++ b/client/src/components/command-palette/routes.ts@@ -0,0 +1,72 @@+import { getSiteRouteContext } from "@/lib/siteRoute";++// Every section the site sidebar links to. Switching site from one of these+// keeps the section; anything deeper (a dashboard, a user profile) falls back+// to that site's main page.+const SITE_SECTION_ROUTES = new Set([+ "main",+ "pages",+ "globe",+ "bots",+ "sessions",+ "replay",+ "users",+ "events",+ "goals",+ "funnels",+ "journeys",+ "retention",+ "errors",+ "performance",+ "api-playground",+ "query",+ "dashboards",+]);++// Site pages that mount a DateSelector. The palette offers date presets only+// where its single-key hotkeys work, so a preset never changes a range nobody+// can see. Keep in sync with the pages that render <SubHeader> or <DateSelector>.+const DATE_SELECTOR_ROUTES = new Set([+ "main",+ "pages",+ "globe",+ "bots",+ "sessions",+ "replay",+ "users",+ "user",+ "events",+ "goals",+ "funnels",+ "journeys",+ "errors",+ "performance",+ "experiments",+]);++const isNumericId = (segment: string | null): segment is string => !!segment && /^\d+$/.test(segment);++/** The site whose pages are open, or null outside a site (home, settings, admin). */+export function getActiveSiteId(pathname: string): number | null {+ const { siteId } = getSiteRouteContext(pathname);+ return isNumericId(siteId) ? Number(siteId) : null;+}++/** True on pages whose DateSelector answers the preset hotkeys. */+export function hasDateSelector(pathname: string): boolean {+ if (pathname === "/" || pathname === "/rollup" || pathname.startsWith("/rollup/")) return true;++ const { siteId, route } = getSiteRouteContext(pathname);+ if (!isNumericId(siteId) || !route) return false;+ // The dashboards list has no range; an open dashboard does.+ if (route === "dashboards") return pathname.split("/").filter(Boolean).length > 2;+ return DATE_SELECTOR_ROUTES.has(route);+}++/** Where switching to `siteId` lands: the same section of the other site, or its main page. */+export function getSwitchSitePath(pathname: string, siteId: number): string {+ const { route } = getSiteRouteContext(pathname);+ const onSite = getActiveSiteId(pathname) !== null;+ const section = onSite && route && SITE_SECTION_ROUTES.has(route) ? route : "main";+ return `/${siteId}/${section}`;+}diff --git a/client/src/components/command-palette/store.ts b/client/src/components/command-palette/store.tsnew file mode 100644index 000000000..aba7b468b--- /dev/null+++ b/client/src/components/command-palette/store.ts@@ -0,0 +1,39 @@+import { create } from "zustand";++export type PaletteOverlay = "palette" | "shortcuts";++// One overlay at a time: the palette can hand over to the shortcut sheet and back.+export const usePaletteOverlay = create<{ overlay: PaletteOverlay | null }>(() => ({ overlay: null }));++// What had focus before the first overlay opened. Radix Dialog only returns+// focus to a Dialog.Trigger, and these overlays open from the keyboard.+let returnFocus: HTMLElement | null = null;++export function showOverlay(overlay: PaletteOverlay) {+ const current = usePaletteOverlay.getState().overlay;+ if (current === overlay) return;++ if (current === null) {+ const active = document.activeElement;+ returnFocus = active instanceof HTMLElement && active !== document.body ? active : null;+ }+ usePaletteOverlay.setState({ overlay });+}++export function closeOverlay() {+ usePaletteOverlay.setState({ overlay: null });+}++export function openCommandPalette() {+ showOverlay("palette");+}++/** `onCloseAutoFocus` for both overlays: focus goes back where it was, unless the other overlay took over. */+export function restoreFocus(event: Event) {+ event.preventDefault();+ if (usePaletteOverlay.getState().overlay !== null) return;++ const target = returnFocus;+ returnFocus = null;+ if (target?.isConnected) target.focus({ preventScroll: true });+}diff --git a/client/src/components/command-palette/useCommandPaletteAvailable.ts b/client/src/components/command-palette/useCommandPaletteAvailable.tsnew file mode 100644index 000000000..16e9e36f0--- /dev/null+++ b/client/src/components/command-palette/useCommandPaletteAvailable.ts@@ -0,0 +1,14 @@+import { usePathname } from "next/navigation";+import { authClient } from "@/lib/auth";+import { getSiteRouteContext } from "@/lib/siteRoute";++/**+ * The palette and the "?" sheet exist for signed-in users. Public dashboards,+ * the claim flow and shared private links are for visitors, so they get+ * neither. (Embeds are checked when a key arrives: see isEmbedView.)+ */+export function useCommandPaletteAvailable(): boolean {+ const { data: session } = authClient.useSession();+ const pathname = usePathname();+ return !!session?.user && !getSiteRouteContext(pathname).privateKey;+}diff --git a/client/src/components/command-palette/usePaletteCommands.tsx b/client/src/components/command-palette/usePaletteCommands.tsxnew file mode 100644index 000000000..5a2800916--- /dev/null+++ b/client/src/components/command-palette/usePaletteCommands.tsx@@ -0,0 +1,385 @@+import { useWindowSize } from "@uidotdev/usehooks";+import {+ AlertTriangle,+ AppWindow,+ Bot,+ Building2,+ Calendar,+ ChartColumnDecreasing,+ Code,+ Combine,+ CreditCard,+ Database,+ File,+ Funnel,+ Gauge,+ Globe2,+ Keyboard,+ LayoutDashboard,+ LayoutGrid,+ Monitor,+ Moon,+ MousePointerClick,+ Rewind,+ Split,+ Sun,+ Target,+ User,+ UserCircle,+ Users,+ Video,+} from "lucide-react";+import { useExtracted } from "next-intl";+import { useTheme } from "next-themes";+import { usePathname, useRouter } from "next/navigation";+import type { ReactNode } from "react";+import { useUserOrganizations } from "@/api/admin/hooks/useOrganizations";+import { useGetSite, useGetSitesFromOrg } from "@/api/admin/hooks/useSites";+import { useGetFunnels } from "@/api/analytics/hooks/funnels/useGetFunnels";+import { useGetGoals } from "@/api/analytics/hooks/goals/useGetGoals";+import { useGetDashboards } from "@/api/analytics/hooks/useDashboards";+import { HOTKEY_FOR_PRESET, PRESET_GROUPS, usePresetLabels } from "@/components/DateSelector/presets";+import { Favicon } from "@/components/Favicon";+import { useAppEnv } from "@/hooks/useIsProduction";+import { authClient } from "@/lib/auth";+import { DEPLOYMENT, IS_CLOUD } from "@/lib/const";+import { getDashboardTimeForRange, setStoredDashboardDefaultTimeRange } from "@/lib/defaultTimeRange";+import { getSiteRouteContext } from "@/lib/siteRoute";+import { useStore, useTimezone } from "@/lib/store";+import { useStripeSubscription } from "@/lib/subscription/useStripeSubscription";+import { getActiveSiteId, getSwitchSitePath, hasDateSelector } from "./routes";+import { showOverlay } from "./store";++export type CommandGroup =+ | "site"+ | "sites"+ | "goals"+ | "funnels"+ | "dashboards"+ | "date"+ | "navigate"+ | "theme"+ | "preferences";++export type PaletteCommand = {+ /** Unique and stable: cmdk tracks the selected row by it. */+ id: string;+ group: CommandGroup;+ label: string;+ /** Extra words the search matches, a little below the label. */+ keywords?: string;+ /** Secondary text beside the label, e.g. a site's domain. */+ hint?: string;+ icon: ReactNode;+ /** Keys that do the same thing outside the palette. */+ shortcut?: string[];+ /** The page, site, range or theme already in effect. */+ current?: boolean;+ run: () => void;+};++/** Rows a data-backed group shows before the user types. Typing searches all of them. */+export const GROUP_LIMITS: Partial<Record<CommandGroup, number>> = { sites: 5, goals: 5, funnels: 5, dashboards: 5 };++const DESKTOP_MIN_WIDTH = 768;++/**+ * Everything the palette can do on the current page, in display order, plus+ * the heading for each group. `entityCommands` (the open site's goals, funnels+ * and dashboards) come from useSiteEntityCommands, which only mounts on a site.+ */+export function usePaletteCommands(entityCommands: PaletteCommand[]): {+ commands: PaletteCommand[];+ groupLabels: Record<CommandGroup, string>;+} {+ const t = useExtracted();+ const router = useRouter();+ const pathname = usePathname();+ const siteId = getActiveSiteId(pathname);+ const { route } = getSiteRouteContext(pathname);++ // The site sidebar's visibility rules, from the same (already cached) queries.+ const { data: siteData } = useGetSite(siteId ?? undefined, { enabled: siteId !== null });+ const site = siteId !== null ? siteData : undefined;+ const { data: subscription, isLoading: isSubscriptionLoading } = useStripeSubscription();+ const appEnv = useAppEnv();+ const { width } = useWindowSize();+ const isDesktop = width === null || width >= DESKTOP_MIN_WIDTH;++ const { data: activeOrganization } = authClient.useActiveOrganization();+ const { data: orgSites } = useGetSitesFromOrg(activeOrganization?.id);+ const { data: userOrganizations } = useUserOrganizations();+ const role = userOrganizations?.find(org => org.id === activeOrganization?.id)?.role;+ const isAdminOrOwner = role === "admin" || role === "owner";++ const time = useStore(state => state.time);+ const setTime = useStore(state => state.setTime);+ const zone = useTimezone();+ const presetLabels = usePresetLabels();+ const { theme, setTheme } = useTheme();++ const go = (path: string, keepSearch = false) => router.push(keepSearch ? `${path}${window.location.search}` : path);++ const isMobileSite = site?.type === "mobile";+ const canReplay =+ isDesktop &&+ !isMobileSite &&+ !subscription?.planName?.startsWith("appsumo") &&+ !isSubscriptionLoading &&+ appEnv !== "demo";+ const canQuery = IS_CLOUD || !!DEPLOYMENT;++ const sections: { route: string; label: string; icon: ReactNode; keywords?: string; visible?: boolean }[] =+ siteId === null+ ? []+ : [+ { route: "main", label: t("Main"), icon: <LayoutDashboard />, keywords: t("overview dashboard") },+ { route: "pages", label: t("Pages"), icon: <File />, visible: IS_CLOUD },+ { route: "globe", label: t("Globe"), icon: <Globe2 />, keywords: t("map") },+ { route: "bots", label: t("Bots"), icon: <Bot />, visible: IS_CLOUD },+ { route: "sessions", label: t("Sessions"), icon: <Rewind /> },+ { route: "replay", label: t("Replay"), icon: <Video />, keywords: t("recordings"), visible: canReplay },+ { route: "users", label: t("Users"), icon: <User /> },+ { route: "events", label: t("Events"), icon: <MousePointerClick /> },+ { route: "goals", label: t("Goals"), icon: <Target /> },+ { route: "funnels", label: t("Funnels"), icon: <Funnel /> },+ { route: "journeys", label: t("Journeys"), icon: <Split /> },+ { route: "retention", label: t("Retention"), icon: <ChartColumnDecreasing /> },+ { route: "errors", label: t("Errors"), icon: <AlertTriangle /> },+ {+ route: "performance",+ label: t("Performance"),+ icon: <Gauge />,+ keywords: t("web vitals"),+ visible: IS_CLOUD && !isMobileSite,+ },+ { route: "api-playground", label: t("API Playground"), icon: <Code />, visible: isDesktop },+ { route: "query", label: t("Query"), icon: <Database />, keywords: t("SQL"), visible: canQuery },+ { route: "dashboards", label: t("Dashboards"), icon: <LayoutGrid />, visible: canQuery },+ ];++ const sectionCommands: PaletteCommand[] = sections+ .filter(section => section.visible !== false)+ .map(section => ({+ id: `site:${section.route}`,+ group: "site",+ label: section.label,+ keywords: section.keywords,+ icon: section.icon,+ current: route === section.route,+ run: () => go(`/${siteId}/${section.route}`, true),+ }));++ const siteCommands: PaletteCommand[] = (orgSites?.sites ?? [])+ .filter(orgSite => orgSite.siteId !== siteId)+ .map(orgSite => ({+ id: `sites:${orgSite.siteId}`,+ group: "sites",+ label: orgSite.name,+ hint: orgSite.domain !== orgSite.name ? orgSite.domain : undefined,+ keywords: orgSite.domain,+ icon: <Favicon domain={orgSite.domain} className="h-4 w-4 rounded-sm" />,+ // Like the site selector: same section, same time and filters.+ run: () => go(getSwitchSitePath(pathname, orgSite.siteId), siteId !== null),+ }));++ const dateKeyword = t("Date range");+ const dateCommands: PaletteCommand[] = hasDateSelector(pathname)+ ? PRESET_GROUPS.flatMap(group => group.presets).map(preset => {+ const hotkey = HOTKEY_FOR_PRESET[preset];+ return {+ id: `date:${preset}`,+ group: "date",+ label: presetLabels[preset],+ keywords: dateKeyword,+ icon: <Calendar />,+ shortcut: hotkey ? [hotkey.toUpperCase()] : undefined,+ current: time.wellKnown === preset,+ // What DateSelector does for a preset hotkey: remember it as the default, then apply it.+ run: () => {+ setStoredDashboardDefaultTimeRange(preset);+ setTime(getDashboardTimeForRange(preset, zone));+ },+ };+ })+ : [];++ const navigateCommands: PaletteCommand[] = [+ {+ id: "nav:home",+ group: "navigate",+ label: t("Home"),+ keywords: t("sites properties"),+ icon: <AppWindow />,+ current: pathname === "/",+ run: () => go("/"),+ },+ {+ id: "nav:rollup",+ group: "navigate",+ label: t("Rollup"),+ keywords: t("all sites"),+ icon: <Combine />,+ current: pathname.startsWith("/rollup"),+ run: () => go("/rollup"),+ },+ {+ id: "nav:account",+ group: "navigate",+ label: t("Account"),+ keywords: t("settings profile password API keys"),+ icon: <UserCircle />,+ current: pathname.startsWith("/settings/account"),+ run: () => go("/settings/account"),+ },+ ];+ // Same rule as the settings navigation: members can't manage the organization.+ if (isAdminOrOwner) {+ navigateCommands.push(+ {+ id: "nav:organization",+ group: "navigate",+ label: t("Organization"),+ keywords: t("settings members invitations"),+ icon: <Building2 />,+ current: pathname.startsWith("/settings/organization"),+ run: () => go("/settings/organization"),+ },+ {+ id: "nav:teams",+ group: "navigate",+ label: t("Teams"),+ icon: <Users />,+ current: pathname.startsWith("/settings/teams"),+ run: () => go("/settings/teams"),+ }+ );+ if (IS_CLOUD) {+ navigateCommands.push({+ id: "nav:billing",+ group: "navigate",+ label: t("Billing"),+ keywords: t("subscription plan invoices"),+ icon: <CreditCard />,+ current: pathname.startsWith("/settings/billing"),+ run: () => go("/settings/billing"),+ });+ }+ }++ const themeKeyword = t("Theme");+ const themeCommands: PaletteCommand[] = [+ { value: "light", label: t("Light"), icon: <Sun /> },+ { value: "dark", label: t("Dark"), icon: <Moon /> },+ { value: "system", label: t("System"), icon: <Monitor /> },+ ].map(option => ({+ id: `theme:${option.value}`,+ group: "theme",+ label: option.label,+ keywords: themeKeyword,+ icon: option.icon,+ current: theme === option.value,+ run: () => setTheme(option.value),+ }));++ const preferenceCommands: PaletteCommand[] = [+ {+ id: "pref:shortcuts",+ group: "preferences",+ label: t("Keyboard shortcuts"),+ keywords: t("hotkeys help"),+ icon: <Keyboard />,+ shortcut: ["?"],+ run: () => showOverlay("shortcuts"),+ },+ ];++ return {+ commands: [+ ...sectionCommands,+ ...siteCommands,+ ...entityCommands,+ ...dateCommands,+ ...navigateCommands,+ ...themeCommands,+ ...preferenceCommands,+ ],+ groupLabels: {+ site: site?.name ?? t("This site"),+ sites: siteId === null ? t("Sites") : t("Switch site"),+ goals: t("Goals"),+ funnels: t("Funnels"),+ dashboards: t("Dashboards"),+ date: dateKeyword,+ navigate: t("Navigate"),+ theme: themeKeyword,+ preferences: t("Preferences"),+ },+ };+}++/**+ * The open site's goals, funnels and dashboards. Mounted only inside the open+ * palette on a site page, so these lists are fetched only while it is open.+ */+export function useSiteEntityCommands(siteId: number): PaletteCommand[] {+ const t = useExtracted();+ const router = useRouter();+ const pathname = usePathname();++ // The goals endpoint caps a page at 100.+ const { data: goals } = useGetGoals({ pageSize: 100 });+ const { data: funnels } = useGetFunnels(siteId);+ const { data: dashboards } = useGetDashboards(IS_CLOUD || DEPLOYMENT ? siteId : undefined);++ // Keep the time and filters, like the sidebar links do.+ const go = (path: string) => router.push(`${path}${window.location.search}`);++ const goalsKeyword = t("Goals");+ const funnelsKeyword = t("Funnels");+ const dashboardsKeyword = t("Dashboards");++ const goalCommands: PaletteCommand[] = (goals?.data ?? []).map(goal => {+ const pattern =+ goal.goalType === "path"+ ? goal.config.pathPattern+ : goal.goalType === "event"+ ? goal.config.eventName+ : goal.config.valuePattern;++ return {+ id: `goal:${goal.goalId}`,+ group: "goals",+ label: goal.name || t("Goal #{goalId}", { goalId: String(goal.goalId) }),+ hint: pattern || undefined,+ keywords: pattern ? `${goalsKeyword} ${pattern}` : goalsKeyword,+ icon: <Target />,+ run: () => go(`/${siteId}/goals`),+ };+ });++ const funnelCommands: PaletteCommand[] = (funnels ?? []).map(funnel => ({+ id: `funnel:${funnel.id}`,+ group: "funnels",+ label: funnel.name,+ hint: t("{count, plural, one {# step} other {# steps}}", { count: funnel.steps.length }),+ keywords: funnelsKeyword,+ icon: <Funnel />,+ run: () => go(`/${siteId}/funnels`),+ }));++ const dashboardCommands: PaletteCommand[] = (dashboards ?? []).map(dashboard => {+ const path = `/${siteId}/dashboards/${dashboard.dashboardId}`;+ return {+ id: `dashboard:${dashboard.dashboardId}`,+ group: "dashboards",+ label: dashboard.name,+ keywords: dashboardsKeyword,+ icon: <LayoutGrid />,+ current: pathname === path,+ run: () => go(path),+ };+ });++ return [...goalCommands, ...funnelCommands, ...dashboardCommands];+}diff --git a/client/src/components/ui/command.tsx b/client/src/components/ui/command.tsxindex 4be3f9bf2..312f00457 100644--- a/client/src/components/ui/command.tsx+++ b/client/src/components/ui/command.tsx@@ -1,11 +1,14 @@"use client";import * as React from "react";+import * as DialogPrimitive from "@radix-ui/react-dialog";import { Command as CommandPrimitive } from "cmdk";+import { AnimatePresence, motion } from "framer-motion";import { SearchIcon } from "lucide-react";import { cn } from "@/lib/utils";-import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { FADE_IN, FADE_OUT, SPRING_PANEL } from "@/lib/motion";+import { Dialog, DialogPortal } from "@/components/ui/dialog";const Command = React.forwardRef<React.ElementRef<typeof CommandPrimitive>,@@ -23,41 +26,82 @@ const Command = React.forwardRef<));Command.displayName = CommandPrimitive.displayName;+type CommandDialogProps = {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ /** Names the dialog for screen readers; not shown. */+ title: string;+ description: string;+ className?: string;+ /** The menu itself, usually a <Command>. */+ children: React.ReactNode;+} & Pick<+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>,+ "onCloseAutoFocus" | "onEscapeKeyDown" | "onKeyDown"+>;++/**+ * A command menu in a Radix Dialog, which supplies the dialog role, focus trap,+ * scroll lock and Escape. The panel sits near the top of the viewport so the+ * input stays put while results change, and floats in on the shared panel+ * spring. Controlled only: the exit animation needs to know when `open` drops.+ */const CommandDialog = ({- title = "Command Palette",- description = "Search for a command to run...",- children,+ open,+ onOpenChange,+ title,+ description,className,- showCloseButton = true,- ...props-}: React.ComponentProps<typeof Dialog> & {- title?: string;- description?: string;- className?: string;- showCloseButton?: boolean;-}) => {- return (- <Dialog {...props}>- <DialogHeader className="sr-only">- <DialogTitle>{title}</DialogTitle>- <DialogDescription>{description}</DialogDescription>- </DialogHeader>- <DialogContent className={cn("overflow-hidden p-0", className)}>- <Command className="[&_[cmdk-group-heading]]:text-muted-foreground [&_[data-slot=command-input-wrapper]]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">- {children}- </Command>- </DialogContent>- </Dialog>- );-};+ children,+ ...contentProps+}: CommandDialogProps) => (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <AnimatePresence>+ {open && (+ <DialogPortal key="command-dialog" forceMount>+ <DialogPrimitive.Overlay asChild forceMount>+ <motion.div+ className="fixed inset-0 z-50 bg-black/25 dark:bg-black/60"+ initial={{ opacity: 0 }}+ animate={{ opacity: 1, transition: FADE_IN }}+ exit={{ opacity: 0, transition: FADE_OUT }}+ />+ </DialogPrimitive.Overlay>+ <DialogPrimitive.Content asChild forceMount {...contentProps}>+ <motion.div+ className={cn(+ "fixed inset-x-0 top-[12vh] z-50 mx-auto flex w-[calc(100%-2rem)] max-w-xl flex-col overflow-hidden rounded-lg border border-neutral-150 bg-white text-neutral-950 shadow-[0_12px_32px_-8px_rgba(0,0,0,0.18),0_1px_2px_rgba(0,0,0,0.06)] outline-none dark:border-neutral-750 dark:bg-neutral-800 dark:text-neutral-50 dark:shadow-[0_12px_32px_-8px_rgba(0,0,0,0.65),0_1px_2px_rgba(0,0,0,0.4)]",+ className+ )}+ initial={{ opacity: 0, scale: 0.96, y: 12 }}+ animate={{ opacity: 1, scale: 1, y: 0, transition: { ...SPRING_PANEL, opacity: FADE_IN } }}+ exit={{ opacity: 0, scale: 0.98, y: 6, transition: FADE_OUT }}+ >+ <DialogPrimitive.Title className="sr-only">{title}</DialogPrimitive.Title>+ <DialogPrimitive.Description className="sr-only">{description}</DialogPrimitive.Description>+ {children}+ </motion.div>+ </DialogPrimitive.Content>+ </DialogPortal>+ )}+ </AnimatePresence>+ </Dialog>+);const CommandInput = React.forwardRef<React.ElementRef<typeof CommandPrimitive.Input>,- React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>->(({ className, ...props }, ref) => (+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input> & {+ wrapperClassName?: string;+ /** Rendered after the input, e.g. a key hint. */+ children?: React.ReactNode;+ }+>(({ className, wrapperClassName, children, ...props }, ref) => (<divdata-slot="command-input-wrapper"- className="flex h-9 items-center gap-2 border-b border-neutral-200 px-3 dark:border-neutral-700"+ className={cn(+ "flex h-9 items-center gap-2 border-b border-neutral-200 px-3 dark:border-neutral-700",+ wrapperClassName+ )}><SearchIcon className="h-4 w-4 shrink-0 opacity-50" /><CommandPrimitive.Input@@ -69,6 +113,7 @@ const CommandInput = React.forwardRef<)}{...props}/>+ {children}</div>));