Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -1,27 +1,47 @@
import "@testing-library/jest-dom";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { act, fireEvent, render, screen, waitFor, type RenderResult } from "@testing-library/react";
import React from "react";
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { UI_SURFACE_IDS } from "~/application/ui/uiRegistry";
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import type { GlobalSearchEntityType, GlobalSearchResponse } from "~/services/search/globalSearch.server";
import { UI_ACTION_IDS, UI_SURFACE_IDS } from "~/application/ui/uiRegistry";
import type { ScopedCommandAction } from "~/services/command-registry/commandRegistry";
import CommandPalette from "./CommandPalette";
type FetcherMock = {
state: "idle" | "loading";
data?: GlobalSearchResponse | { error: string };
load: ReturnType<typeof vi.fn>;
submit: ReturnType<typeof vi.fn>;
};
type CommandPaletteTestState = {
navigate: ReturnType<typeof vi.fn>;
openWindow: ReturnType<typeof vi.fn>;
getCommandRegistryActions: ReturnType<typeof vi.fn>;
useAppOrAdminData: ReturnType<typeof vi.fn>;
useRootData: ReturnType<typeof vi.fn>;
actionFetcher: FetcherMock;
searchFetcher: FetcherMock;
recentFetcher: FetcherMock;
};
declare global {
var __commandPaletteTest: CommandPaletteTestState;
}
function createFetcher(): FetcherMock {
return { state: "idle", data: undefined, load: vi.fn().mockResolvedValue(undefined), submit: vi.fn() };
}
globalThis.__commandPaletteTest = {
navigate: vi.fn(),
openWindow: vi.fn(),
getCommandRegistryActions: vi.fn(),
useAppOrAdminData: vi.fn(),
useRootData: vi.fn(),
actionFetcher: createFetcher(),
searchFetcher: createFetcher(),
recentFetcher: createFetcher(),
};
globalThis.ResizeObserver =
@@ -34,14 +54,18 @@ globalThis.ResizeObserver =
HTMLElement.prototype.scrollIntoView = HTMLElement.prototype.scrollIntoView ?? vi.fn();
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (value: string) => value }),
useTranslation: () => ({ t: (value: string) => value, i18n: { language: "en" } }),
}));
vi.mock("react-router", async () => {
const actual = await vi.importActual<typeof import("react-router")>("react-router");
return {
...actual,
useFetcher: () => ({ submit: vi.fn() }),
useFetcher: (options?: { key?: string }) => {
if (options?.key === "command-palette-search") return globalThis.__commandPaletteTest.searchFetcher;
if (options?.key === "command-palette-recent") return globalThis.__commandPaletteTest.recentFetcher;
return globalThis.__commandPaletteTest.actionFetcher;
},
useNavigate: () => globalThis.__commandPaletteTest.navigate,
};
});
@@ -58,111 +82,452 @@ vi.mock("~/services/command-registry/commandRegistry", () => ({
getCommandRegistryActions: (...args: unknown[]) => globalThis.__commandPaletteTest.getCommandRegistryActions(...args),
}));
const appData = { currentTenant: { slug: "acme" } };
const rootData = { appConfiguration: { app: { features: {} } } };
const appData = { currentTenant: { slug: "acme" }, permissions: ["search.use"] };
const rootData = { csrf: "csrf-token", appConfiguration: { app: { features: {} } } };
function renderPalette(props?: Partial<React.ComponentProps<typeof CommandPalette>>) {
return render(
function paletteElement(props?: Partial<React.ComponentProps<typeof CommandPalette>>) {
return (
<CommandPalette layout="app" {...props}>
<button data-ui-id={UI_ACTION_IDS.search}>Open search</button>
<button data-ui-id={UI_ACTION_IDS.searchMobile}>Open mobile search</button>
<div>Palette child</div>
</CommandPalette>
);
}
function renderPalette(props?: Partial<React.ComponentProps<typeof CommandPalette>>) {
return render(paletteElement(props));
}
function openPalette() {
fireEvent.keyDown(window, { key: "k", metaKey: true });
}
function openPaletteWithCtrl() {
fireEvent.keyDown(window, { key: "k", ctrlKey: true });
}
function searchInput() {
return document.querySelector<HTMLInputElement>(`[data-ui-id="${UI_SURFACE_IDS.commandPaletteSearch}"]`)!;
}
function lastSearchRequest() {
const url = globalThis.__commandPaletteTest.searchFetcher.load.mock.calls.at(-1)?.[0] as string;
return new URL(url, "https://app.example.test");
}
function resultRow(entityType: GlobalSearchEntityType, entityId: string) {
const normalizedId = entityId
.split(/[^a-zA-Z0-9]+/u)
.filter(Boolean)
.map((word, index) => (index === 0 ? word.toLowerCase() : `${word.charAt(0).toUpperCase()}${word.slice(1).toLowerCase()}`))
.join("");
return document.querySelector<HTMLElement>(`[data-ui-id="ui.surface.commandPalette.result.${entityType}.${normalizedId}"]`)!;
}
function searchResponse(requestUrl: URL, overrides: Partial<GlobalSearchResponse> = {}): GlobalSearchResponse {
const query = requestUrl.searchParams.get("q") ?? "";
const requestedEntityTypes = requestUrl.searchParams.getAll("type") as GlobalSearchEntityType[];
const requestId = requestUrl.searchParams.get("requestId");
const limit = requestUrl.searchParams.get("limit") ?? "20";
return {
query,
requestedEntityTypes,
requestId,
requestKey: `${encodeURIComponent(query)}|${requestedEntityTypes.join(",") || "*"}|${limit}`,
results: [],
recentSearches: [],
hiddenEntityTypes: [],
latencyHint: "Search index updates can take up to 10 seconds.",
...overrides,
};
}
async function sendSearchQuery(query: string) {
vi.useFakeTimers();
fireEvent.change(searchInput(), { target: { value: query } });
await act(async () => {
await vi.advanceTimersByTimeAsync(300);
});
vi.useRealTimers();
return lastSearchRequest();
}
async function applySearchResponse(
view: RenderResult,
response: GlobalSearchResponse | { error: string },
props?: Partial<React.ComponentProps<typeof CommandPalette>>
) {
globalThis.__commandPaletteTest.searchFetcher.state = "idle";
globalThis.__commandPaletteTest.searchFetcher.data = response;
view.rerender(paletteElement(props));
await act(async () => undefined);
}
describe("CommandPalette", () => {
// CommandPaletteDialog wird in der Komponente per React.lazy(() => import("./CommandPaletteDialog"))
// geladen. In der vollen Suite kann der KALTE erste dynamische Import unter CPU-Last die
// 1000ms-Default-Frist von findByText reissen (erster Test rot, danach Modul warm -> gruen).
// Vorwaermen macht den ersten Oeffnen-Pfad deterministisch synchron.
beforeAll(async () => {
await import("./CommandPaletteDialog");
});
}, 60000);
beforeEach(() => {
const state = globalThis.__commandPaletteTest;
state.navigate.mockReset();
state.openWindow.mockReset();
state.getCommandRegistryActions.mockReset();
state.useAppOrAdminData.mockReset();
state.useRootData.mockReset();
state.actionFetcher = createFetcher();
state.searchFetcher = createFetcher();
state.recentFetcher = createFetcher();
state.useAppOrAdminData.mockReturnValue(appData);
state.useRootData.mockReturnValue(rootData);
state.getCommandRegistryActions.mockReturnValue([
{ id: "registry-dashboard", name: "Dashboard", subtitle: "App", perform: vi.fn(), scope: { layout: "app", tenantSlug: "acme" } },
{ id: "registry-denied-looking", name: "Denied Looking", subtitle: "Filtered upstream", perform: vi.fn(), scope: { layout: "app", tenantSlug: "acme", permission: "entity.contacts.view" } },
{ id: "registry-profile", name: "Profile", subtitle: "Settings", perform: vi.fn(), scope: { layout: "app", tenantSlug: "acme" } },
]);
vi.spyOn(window, "open").mockImplementation(state.openWindow);
});
function openPalette() {
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
});
it("passes registry actions through and opens from Cmd+K or Ctrl+K", async () => {
const view = renderPalette();
openPalette();
await screen.findByText("Dashboard", undefined, { timeout: 4000 });
expect(globalThis.__commandPaletteTest.getCommandRegistryActions).toHaveBeenCalledWith(
expect.objectContaining({ layout: "app", navigate: globalThis.__commandPaletteTest.navigate, appData, rootData })
);
expect(screen.getByText("Palette child")).toBeInTheDocument();
expect(document.querySelector('[data-ui-id="ui.surface.commandPalette.action.registryDashboard"]')).toBeInTheDocument();
fireEvent.keyDown(window, { key: "k", metaKey: true });
}
function openPaletteWithCtrl() {
fireEvent.keyDown(window, { key: "k", ctrlKey: true });
}
it("passes the filtered registry-backed actions through for the active layout context", async () => {
renderPalette();
const state = globalThis.__commandPaletteTest;
expect(state.getCommandRegistryActions).not.toHaveBeenCalled();
openPalette();
await screen.findByText("Dashboard", undefined, { timeout: 4000 });
expect(state.getCommandRegistryActions).toHaveBeenCalledWith(expect.objectContaining({
layout: "app",
t: expect.any(Function),
navigate: state.navigate,
appData,
rootData,
}));
expect(screen.getByText("Denied Looking")).toBeInTheDocument();
expect(screen.getByText("Palette child")).toBeInTheDocument();
});
it("uses a custom actions prop instead of registry actions", async () => {
const customActions: ScopedCommandAction[] = [{ id: "custom-action", name: "Custom Action", perform: vi.fn(), scope: { layout: "app" } }];
renderPalette({ actions: customActions });
const state = globalThis.__commandPaletteTest;
expect(state.getCommandRegistryActions).not.toHaveBeenCalled();
openPalette();
expect(await screen.findByText("Custom Action")).toBeInTheDocument();
expect(state.getCommandRegistryActions).not.toHaveBeenCalled();
});
it("opens from the Windows/Linux Ctrl+K shortcut", async () => {
renderPalette();
expect(screen.queryByText("Dashboard")).not.toBeInTheDocument();
openPaletteWithCtrl();
await screen.findByText("Dashboard", undefined, { timeout: 4000 });
expect(screen.getByText("Denied Looking")).toBeInTheDocument();
expect(await screen.findByText("Dashboard")).toBeInTheDocument();
view.unmount();
});
it("renders a safe empty path when app/root data is missing", async () => {
const state = globalThis.__commandPaletteTest;
state.useAppOrAdminData.mockReturnValue(undefined);
state.useRootData.mockReturnValue(undefined);
state.getCommandRegistryActions.mockReturnValue([]);
renderPalette();
it("uses custom actions without consulting the registry", async () => {
const customActions: ScopedCommandAction[] = [{ id: "custom-action", name: "Custom Action", perform: vi.fn(), scope: { layout: "app" } }];
renderPalette({ actions: customActions });
openPalette();
await waitFor(() => {
expect(state.getCommandRegistryActions).toHaveBeenCalledWith(expect.objectContaining({ appData: undefined, rootData: undefined }));
expect(await screen.findByText("Custom Action")).toBeInTheDocument();
expect(globalThis.__commandPaletteTest.getCommandRegistryActions).not.toHaveBeenCalled();
});
it("debounces global search, requests 20 results, and does not reload after accepting a response", async () => {
const view = renderPalette();
openPalette();
await screen.findByText("search.command.minimumCharacters");
await waitFor(() => expect(globalThis.__commandPaletteTest.searchFetcher.load).toHaveBeenCalledTimes(1));
vi.useFakeTimers();
fireEvent.change(searchInput(), { target: { value: "solar" } });
await act(async () => {
await vi.advanceTimersByTimeAsync(299);
});
expect(screen.getByText("Palette child")).toBeInTheDocument();
expect(globalThis.__commandPaletteTest.searchFetcher.load).toHaveBeenCalledTimes(1);
await act(async () => {
await vi.advanceTimersByTimeAsync(1);
});
vi.useRealTimers();
const request = lastSearchRequest();
expect(request.pathname).toContain("/search/api");
expect(request.searchParams.get("q")).toBe("solar");
expect(request.searchParams.get("limit")).toBe("20");
expect(request.searchParams.getAll("type")).toEqual(["contact", "company", "lead", "project", "file", "task", "employee", "user"]);
expect(request.searchParams.get("requestId")).toMatch(/^spotlight-/);
await applySearchResponse(view, searchResponse(request));
await screen.findByText("search.results.empty");
await act(async () => undefined);
expect(globalThis.__commandPaletteTest.searchFetcher.load).toHaveBeenCalledTimes(2);
});
it("renders stable data-ui-id attributes for command palette surfaces and rows", async () => {
it("rejects a stale response after filters change and renders the current grouped response with permission hint", async () => {
const view = renderPalette();
openPalette();
await screen.findByText("search.command.minimumCharacters");
const firstRequest = await sendSearchQuery("solar");
vi.useFakeTimers();
fireEvent.click(screen.getByRole("button", { name: "search.entities.user" }));
await act(async () => {
await vi.advanceTimersByTimeAsync(300);
});
vi.useRealTimers();
const currentRequest = lastSearchRequest();
expect(currentRequest.searchParams.get("requestId")).not.toBe(firstRequest.searchParams.get("requestId"));
expect(currentRequest.searchParams.getAll("type")).toEqual(["user"]);
await applySearchResponse(
view,
searchResponse(firstRequest, {
results: [
{
id: "stale",
entityType: "project",
title: "Stale solar project",
subtitle: "P-0",
href: "/projects/stale",
permissionSubject: "projects.read_all",
updatedAt: null,
},
],
})
);
expect(screen.queryByText("Stale solar project")).not.toBeInTheDocument();
await applySearchResponse(
view,
searchResponse(currentRequest, {
hiddenEntityTypes: ["user"],
results: [
{
id: "project-1",
entityType: "project",
title: "Solar roof",
subtitle: "P-100",
href: "/projects/project-1",
permissionSubject: "projects.read_all",
updatedAt: "2026-07-12T08:00:00.000Z",
},
{
id: "contact-1",
entityType: "contact",
title: "Solaris GmbH",
subtitle: "info@solaris.test",
href: "/contacts/contact-1",
permissionSubject: "crm.read_all",
updatedAt: null,
},
],
})
);
await waitFor(() => expect(resultRow("project", "project-1")).toHaveTextContent("Solar roof"));
const headings = [...document.querySelectorAll("[cmdk-group-heading]")].map((node) => node.textContent);
expect(headings.indexOf("search.entities.contact")).toBeLessThan(headings.indexOf("search.entities.project"));
expect(screen.getByText("search.results.hidden")).toBeInTheDocument();
expect(document.querySelector("mark")).toHaveTextContent(/solar/i);
});
it("narrows to a single category on the first tile click and resets to all when the last one is deselected", async () => {
renderPalette();
openPalette();
await screen.findByText("search.command.minimumCharacters");
await sendSearchQuery("solar");
async function clickTile(entityType: GlobalSearchEntityType) {
vi.useFakeTimers();
fireEvent.click(screen.getByRole("button", { name: `search.entities.${entityType}` }));
await act(async () => {
await vi.advanceTimersByTimeAsync(300);
});
vi.useRealTimers();
return lastSearchRequest().searchParams.getAll("type");
}
// All selected by default: first click focuses on the clicked category only.
expect(await clickTile("project")).toEqual(["project"]);
// Further clicks toggle categories in canonical order.
expect(await clickTile("contact")).toEqual(["contact", "project"]);
expect(await clickTile("contact")).toEqual(["project"]);
// Deselecting the last active category resets back to all.
expect(await clickTile("project")).toEqual(["contact", "company", "lead", "project", "file", "task", "employee", "user"]);
});
it("shows loading, error, empty, short-query, and recent-search states", async () => {
const view = renderPalette();
openPalette();
expect(await screen.findByText("search.command.minimumCharacters")).toBeInTheDocument();
const recentRequest = lastSearchRequest();
await applySearchResponse(
view,
searchResponse(recentRequest, {
recentSearches: [{ id: "recent-1", queryText: "heat pump", entityTypes: ["project", "task"], resultCount: 4, createdAt: "2026-07-12T08:00:00.000Z" }],
})
);
expect(await screen.findByText("heat pump")).toBeInTheDocument();
vi.useFakeTimers();
fireEvent.change(searchInput(), { target: { value: "nothing" } });
globalThis.__commandPaletteTest.searchFetcher.state = "loading";
view.rerender(paletteElement());
expect(screen.getByText("search.command.loading")).toBeInTheDocument();
await act(async () => {
await vi.advanceTimersByTimeAsync(300);
});
vi.useRealTimers();
const emptyRequest = lastSearchRequest();
await applySearchResponse(view, searchResponse(emptyRequest));
expect(await screen.findByText("search.results.empty")).toBeInTheDocument();
await applySearchResponse(view, { error: "invalid_request_id" });
expect(await screen.findByText("search.command.error")).toBeInTheDocument();
const requestsBeforeRetry = globalThis.__commandPaletteTest.searchFetcher.load.mock.calls.length;
vi.useFakeTimers();
fireEvent.click(screen.getByRole("button", { name: "shared.retry" }));
await act(async () => {
await vi.advanceTimersByTimeAsync(300);
});
vi.useRealTimers();
expect(globalThis.__commandPaletteTest.searchFetcher.load).toHaveBeenCalledTimes(requestsBeforeRetry + 1);
});
it("records a committed selection without waiting before Enter navigates in the same tab", async () => {
const view = renderPalette();
openPalette();
await screen.findByText("search.command.minimumCharacters");
const request = await sendSearchQuery("anna");
await applySearchResponse(
view,
searchResponse(request, {
results: [
{
id: "contact-1",
entityType: "contact",
title: "Anna Becker",
subtitle: "anna@example.test",
href: "/contacts/contact-1",
permissionSubject: "crm.read_all",
updatedAt: null,
},
],
})
);
await waitFor(() => expect(resultRow("contact", "contact-1")).toHaveTextContent("Anna Becker"));
const row = resultRow("contact", "contact-1");
row.focus();
fireEvent.keyDown(row, { key: "Enter" });
expect(globalThis.__commandPaletteTest.navigate).toHaveBeenCalledWith("/contacts/contact-1");
expect(globalThis.__commandPaletteTest.recentFetcher.submit).toHaveBeenCalledTimes(1);
const [form, options] = globalThis.__commandPaletteTest.recentFetcher.submit.mock.calls[0]!;
expect(form).toBeInstanceOf(FormData);
expect((form as FormData).get("intent")).toBe("recordRecent");
expect((form as FormData).get("query")).toBe("anna");
expect((form as FormData).get("selectedEntityType")).toBe("contact");
expect((form as FormData).get("selectedEntityId")).toBe("contact-1");
expect((form as FormData).get("csrf")).toBe("csrf-token");
expect(options).toEqual(expect.objectContaining({ method: "post", action: expect.stringContaining("/search/api") }));
});
it.each([
{ label: "Cmd", modifier: "metaKey" as const },
{ label: "Ctrl", modifier: "ctrlKey" as const },
])("opens the selected result in a new tab with $label+Enter", async ({ modifier }) => {
const view = renderPalette();
openPalette();
await screen.findByText("search.command.minimumCharacters");
const request = await sendSearchQuery("quote");
await applySearchResponse(
view,
searchResponse(request, {
results: [
{
id: "file-1",
entityType: "file",
title: "Quote.pdf",
subtitle: "application/pdf",
href: "/files/file-1",
permissionSubject: "files.read_all",
updatedAt: null,
},
],
})
);
await waitFor(() => expect(resultRow("file", "file-1")).toHaveTextContent("Quote.pdf"));
const row = resultRow("file", "file-1");
row.focus();
fireEvent.keyDown(row, { key: "Enter", [modifier]: true });
await waitFor(() => expect(globalThis.__commandPaletteTest.openWindow).toHaveBeenCalledWith("/files/file-1", "_blank", "noopener,noreferrer"));
expect(globalThis.__commandPaletteTest.navigate).not.toHaveBeenCalled();
});
it("loads one additional page inside the modal up to the 50-result cap", async () => {
const view = renderPalette();
openPalette();
await screen.findByText("search.command.minimumCharacters");
const request = await sendSearchQuery("project");
const results = Array.from({ length: 20 }, (_, index) => ({
id: `project-${index}`,
entityType: "project" as const,
title: `Project ${index}`,
subtitle: `P-${index}`,
href: `/projects/project-${index}`,
permissionSubject: "projects.read_all",
updatedAt: null,
}));
await applySearchResponse(view, searchResponse(request, { results }));
const loadMore = await screen.findByRole("button", { name: "search.command.loadMore" });
vi.useFakeTimers();
fireEvent.click(loadMore);
await act(async () => {
await vi.advanceTimersByTimeAsync(300);
});
vi.useRealTimers();
const expandedRequest = lastSearchRequest();
expect(expandedRequest.searchParams.get("limit")).toBe("50");
await applySearchResponse(view, searchResponse(expandedRequest, { results }));
expect(screen.queryByRole("button", { name: "search.command.loadMore" })).not.toBeInTheDocument();
});
it("renders unique registry-backed UI IDs for the mobile/desktop Spotlight surfaces and rows", async () => {
const view = renderPalette();
openPalette();
await screen.findByText("search.command.minimumCharacters");
const request = await sendSearchQuery("solar");
await applySearchResponse(
view,
searchResponse(request, {
results: [
{
id: "project-1",
entityType: "project",
title: "Solar roof",
subtitle: "P-100",
href: "/projects/project-1",
permissionSubject: "projects.read_all",
updatedAt: null,
},
],
})
);
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.commandPalettePortal}"]`)).toHaveClass("h-dvh", "sm:h-auto");
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.commandPaletteSearch}"]`)).toBeInTheDocument();
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.commandPaletteFilters}"]`)).toBeInTheDocument();
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.commandPaletteResults}"]`)).toBeInTheDocument();
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.commandPaletteFooter}"]`)).toBeInTheDocument();
const ids = [...document.querySelectorAll("[data-ui-id]")].map((element) => element.getAttribute("data-ui-id"));
expect(new Set(ids).size).toBe(ids.length);
expect(ids).toContain("ui.surface.commandPalette.result.project.project1");
});
it("renders a safe action-only palette when app/root data is missing", async () => {
globalThis.__commandPaletteTest.useAppOrAdminData.mockReturnValue(undefined);
globalThis.__commandPaletteTest.useRootData.mockReturnValue(undefined);
globalThis.__commandPaletteTest.getCommandRegistryActions.mockReturnValue([]);
renderPalette();
openPalette();
await screen.findByText("Dashboard", undefined, { timeout: 4000 });
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.commandPalettePortal}"]`)).toBeInTheDocument();
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.commandPaletteSearch}"]`)).toBeInTheDocument();
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.commandPaletteResults}"]`)).toBeInTheDocument();
expect(document.querySelectorAll(`[data-ui-id="${UI_SURFACE_IDS.commandPaletteRow}"]`)).toHaveLength(2);
expect(screen.getByText("Dashboard")).toBeInTheDocument();
expect(screen.getByText("Denied Looking")).toBeInTheDocument();
expect(await screen.findByText("app.commands.empty.title")).toBeInTheDocument();
expect(globalThis.__commandPaletteTest.searchFetcher.load).not.toHaveBeenCalled();
});
});
@@ -1,16 +1,27 @@
import { useEffect, useMemo, useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useFetcher, useNavigate } from "react-router";
import { UI_SURFACE_IDS } from "~/application/ui/uiRegistry";
import { CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "~/components/ui/command";
import {
buildSpotlightSearchGroups,
type SpotlightSearchDialogVM,
type SpotlightSearchEntityType,
type SpotlightSearchItemVM,
type SpotlightSearchRecentVM,
} from "@hivegrid/view-models";
import { UI_ACTION_IDS } from "~/application/ui/uiRegistry";
import type { GlobalSearchEntityType, GlobalSearchResponse } from "~/services/search/globalSearch.server";
import { getCommandRegistryActions, type CommandRegistryLayout, type ScopedCommandAction } from "~/services/command-registry/commandRegistry";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import type { AppLoaderData } from "~/utils/data/useAppData";
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
import { useRootData } from "~/utils/data/useRootData";
import { SpotlightSearchDialogView } from "./SpotlightSearchDialogView";
const globalSearchEntityTypes: GlobalSearchEntityType[] = ["contact", "company", "lead", "project", "file", "task", "user"];
const INITIAL_RESULT_LIMIT = 20;
const MAX_RESULT_LIMIT = 50;
const SEARCH_DEBOUNCE_MS = 300;
const globalSearchEntityTypes: GlobalSearchEntityType[] = ["contact", "company", "lead", "project", "file", "task", "employee", "user"];
type SearchFetcherData = GlobalSearchResponse | { error: string };
export default function CommandPaletteDialog({
actions,
@@ -25,35 +36,91 @@ export default function CommandPaletteDialog({
}) {
const { t, i18n } = useTranslation();
const navigate = useNavigate();
const fetcher = useFetcher();
const searchFetcher = useFetcher<GlobalSearchResponse>();
const fetcher = useFetcher({ key: "command-palette-actions" });
const searchFetcher = useFetcher<SearchFetcherData>({ key: "command-palette-search" });
const recentFetcher = useFetcher({ key: "command-palette-recent" });
const appData = useAppOrAdminData() as AppLoaderData | undefined;
const rootData = useRootData();
const [query, setQuery] = useState("");
const [selectedEntityTypes, setSelectedEntityTypes] = useState<GlobalSearchEntityType[]>(globalSearchEntityTypes);
const [resultLimit, setResultLimit] = useState(INITIAL_RESULT_LIMIT);
const [expectedRequestId, setExpectedRequestId] = useState<string | null>(null);
const [acceptedRequestId, setAcceptedRequestId] = useState<string | null>(null);
const [isDebouncing, setIsDebouncing] = useState(false);
const [searchFailed, setSearchFailed] = useState(false);
const [retryVersion, setRetryVersion] = useState(0);
const requestSequence = useRef(0);
const pendingRequestId = useRef<string | null>(null);
const openSelectionInNewTab = useRef(false);
const searchLoad = useRef(searchFetcher.load);
searchLoad.current = searchFetcher.load;
const canUseGlobalSearch = layout === "app" && !!appData?.currentTenant?.slug && appData.permissions?.includes("search.use");
const trimmedQuery = query.trim();
const searchResults = searchFetcher.data?.query === trimmedQuery ? (searchFetcher.data.results ?? []) : [];
const recentSearches = searchFetcher.data?.query === "" ? (searchFetcher.data.recentSearches ?? []) : [];
const activeTypeParams = useMemo(() => selectedEntityTypes.map((type) => `type=${encodeURIComponent(type)}`).join("&"), [selectedEntityTypes]);
const allResultsHref = useMemo(() => {
if (!appData?.currentTenant?.slug) return "";
const suffix = activeTypeParams ? `&${activeTypeParams}` : "";
return appPath({ tenantSlug: appData.currentTenant.slug, path: `search?q=${encodeURIComponent(trimmedQuery)}${suffix}`, mode: "host-aware" });
}, [activeTypeParams, appData?.currentTenant?.slug, trimmedQuery]);
const isSearchQuery = trimmedQuery.length >= 2;
const canonicalSelectedEntityTypes = useMemo(() => globalSearchEntityTypes.filter((type) => selectedEntityTypes.includes(type)), [selectedEntityTypes]);
const activeTypeParams = useMemo(
() => canonicalSelectedEntityTypes.map((type) => `type=${encodeURIComponent(type)}`).join("&"),
[canonicalSelectedEntityTypes]
);
const currentResponse =
isGlobalSearchResponse(searchFetcher.data) &&
searchFetcher.data.requestId &&
searchFetcher.data.requestId === expectedRequestId &&
searchFetcher.data.requestId === acceptedRequestId
? searchFetcher.data
: undefined;
const searchResults = isSearchQuery && currentResponse?.query === trimmedQuery ? currentResponse.results : [];
const recentSearches = !isSearchQuery && currentResponse?.query === "" ? currentResponse.recentSearches : [];
const searchGroups = useMemo(() => buildSpotlightSearchGroups(searchResults), [searchResults]);
const isLoading = canUseGlobalSearch && !searchFailed && (isDebouncing || searchFetcher.state !== "idle" || expectedRequestId !== acceptedRequestId);
const hiddenEntityTypes = currentResponse?.hiddenEntityTypes ?? [];
const canLoadMore = isSearchQuery && !isLoading && !searchFailed && resultLimit === INITIAL_RESULT_LIMIT && searchResults.length === INITIAL_RESULT_LIMIT;
useEffect(() => {
if (!open || !canUseGlobalSearch || !appData?.currentTenant?.slug) return;
if (trimmedQuery.length < 2) {
searchFetcher.load(appPath({ tenantSlug: appData.currentTenant.slug, path: "search/api?limit=6", mode: "host-aware" }));
const requestId = `spotlight-${++requestSequence.current}`;
pendingRequestId.current = requestId;
setExpectedRequestId(requestId);
setAcceptedRequestId(null);
setSearchFailed(false);
const typeSuffix = activeTypeParams ? `&${activeTypeParams}` : "";
const loadSearch = (path: string) => {
void searchLoad.current(appPath({ tenantSlug: appData.currentTenant.slug, path, mode: "host-aware" })).catch(() => {
if (pendingRequestId.current === requestId) {
setSearchFailed(true);
setIsDebouncing(false);
}
});
};
if (!isSearchQuery) {
setIsDebouncing(false);
loadSearch(`search/api?limit=6&requestId=${encodeURIComponent(requestId)}`);
return;
}
const typeSuffix = activeTypeParams ? `&${activeTypeParams}` : "";
setIsDebouncing(true);
const timeout = window.setTimeout(() => {
searchFetcher.load(appPath({ tenantSlug: appData.currentTenant.slug, path: `search/api?q=${encodeURIComponent(trimmedQuery)}&limit=6${typeSuffix}`, mode: "host-aware" }));
}, 300);
setIsDebouncing(false);
loadSearch(`search/api?q=${encodeURIComponent(trimmedQuery)}&limit=${resultLimit}${typeSuffix}&requestId=${encodeURIComponent(requestId)}`);
}, SEARCH_DEBOUNCE_MS);
return () => window.clearTimeout(timeout);
}, [activeTypeParams, appData?.currentTenant?.slug, canUseGlobalSearch, open, searchFetcher, trimmedQuery]);
}, [activeTypeParams, appData?.currentTenant?.slug, canUseGlobalSearch, isSearchQuery, open, resultLimit, retryVersion, trimmedQuery]);
useEffect(() => {
if (searchFetcher.state !== "idle" || !searchFetcher.data) return;
if (!isGlobalSearchResponse(searchFetcher.data)) {
setSearchFailed(true);
setIsDebouncing(false);
return;
}
if (!searchFetcher.data.requestId) return;
if (searchFetcher.data.requestId !== pendingRequestId.current) return;
setAcceptedRequestId(searchFetcher.data.requestId);
setSearchFailed(false);
}, [searchFetcher.data, searchFetcher.state]);
const resolvedActions =
actions ??
@@ -65,154 +132,144 @@ export default function CommandPaletteDialog({
navigate,
submitLogout: () => {
const form = new FormData();
if (rootData?.csrf) {
form.set("csrf", rootData.csrf);
}
if (rootData?.csrf) form.set("csrf", rootData.csrf);
fetcher.submit(form, { method: "post", action: "/logout" });
},
appData,
rootData,
})
: []);
const visibleActions = useMemo(() => {
const normalizedQuery = trimmedQuery.toLocaleLowerCase();
const matches = normalizedQuery
? resolvedActions.filter((action) =>
[action.name, action.subtitle, action.keywords, action.id].filter(Boolean).join(" ").toLocaleLowerCase().includes(normalizedQuery)
)
: resolvedActions;
return matches.slice(0, isSearchQuery ? 4 : 8);
}, [isSearchQuery, resolvedActions, trimmedQuery]);
function updateQuery(value: string) {
setQuery(value);
setResultLimit(INITIAL_RESULT_LIMIT);
}
function toggleEntityType(type: GlobalSearchEntityType) {
setSelectedEntityTypes((current) => {
// Default state is "all selected": the first tile click narrows to that category only.
if (current.length === globalSearchEntityTypes.length) {
return [type];
}
if (current.includes(type)) {
const next = current.filter((entry) => entry !== type);
// Deselecting the last active category resets back to "all selected".
return next.length > 0 ? next : globalSearchEntityTypes;
}
return globalSearchEntityTypes.filter((entry) => entry === type || current.includes(entry));
});
setResultLimit(INITIAL_RESULT_LIMIT);
}
function recordCommittedSelection(item: SpotlightSearchItemVM) {
if (!appData?.currentTenant?.slug || !rootData?.csrf) return;
const form = new FormData();
form.set("intent", "recordRecent");
form.set("query", trimmedQuery);
form.set("resultCount", String(searchResults.length));
canonicalSelectedEntityTypes.forEach((type) => form.append("type", type));
form.set("selectedEntityType", item.entityType);
form.set("selectedEntityId", item.id);
form.set("csrf", rootData.csrf);
recentFetcher.submit(form, {
method: "post",
action: appPath({ tenantSlug: appData.currentTenant.slug, path: "search/api", mode: "host-aware" }),
});
}
function openResult(item: SpotlightSearchItemVM) {
recordCommittedSelection(item);
const shouldOpenNewTab = openSelectionInNewTab.current;
openSelectionInNewTab.current = false;
if (shouldOpenNewTab) {
window.open(item.href, "_blank", "noopener,noreferrer");
} else {
navigate(item.href);
}
setOpen(false);
}
const searchState: SpotlightSearchDialogVM["searchState"] = !canUseGlobalSearch
? "idle"
: isLoading
? "loading"
: searchFailed
? "error"
: isSearchQuery && currentResponse && searchGroups.length === 0
? "empty"
: currentResponse
? "ready"
: "idle";
const vm = {
open,
query,
selectedEntityTypes: canonicalSelectedEntityTypes,
canUseGlobalSearch,
isSearchQuery,
searchState,
hasResolvedResponse: !!currentResponse,
searchGroups: searchGroups.map((group) => ({ ...group, items: [...group.items] })),
recentSearches: recentSearches.map(({ id, queryText, entityTypes, resultCount }) => ({ id, queryText, entityTypes, resultCount })),
hiddenEntityTypes,
canLoadMore,
visibleActions: visibleActions.map((action) => ({
id: action.id,
name: action.name,
subtitle: action.subtitle ?? null,
searchValue: [action.name, action.subtitle, action.keywords, action.id].filter(Boolean).join(" "),
})),
} satisfies SpotlightSearchDialogVM;
return (
<div>
<CommandDialog
open={open}
onOpenChange={setOpen}
dataUiId={UI_SURFACE_IDS.commandPalettePortal}
onCloseAutoFocus={(event) => {
// The palette opens via controlled state, not a Radix trigger, so Radix
// drops focus to <body> on close. Return focus to the search trigger.
const trigger = typeof document !== "undefined" ? document.querySelector<HTMLElement>('[data-ui-id="ui.action.shell.search"]') : null;
<SpotlightSearchDialogView
vm={vm}
actions={{
onOpenChange: setOpen,
onQueryChange: updateQuery,
onToggleEntityType: (entityType: SpotlightSearchEntityType) => toggleEntityType(entityType),
onSelectRecent: (recent: SpotlightSearchRecentVM) => {
if (recent.entityTypes.length > 0) setSelectedEntityTypes(recent.entityTypes);
updateQuery(recent.queryText);
},
onPrepareResultSelection: () => {
openSelectionInNewTab.current = false;
},
onSelectResult: openResult,
onLoadMore: () => setResultLimit(MAX_RESULT_LIMIT),
onRetry: () => setRetryVersion((current) => current + 1),
onSelectAction: (actionId) => {
const action = visibleActions.find((candidate) => candidate.id === actionId);
action?.perform?.(action);
setOpen(false);
},
onCommandKeyDownCapture: (event) => {
if (event.key === "Enter") openSelectionInNewTab.current = event.metaKey || event.ctrlKey;
},
onCloseAutoFocus: (event) => {
const triggers =
typeof document !== "undefined"
? Array.from(document.querySelectorAll<HTMLElement>(`[data-ui-id="${UI_ACTION_IDS.searchMobile}"], [data-ui-id="${UI_ACTION_IDS.search}"]`))
: [];
const trigger = triggers.find((candidate) => candidate.offsetParent !== null) ?? triggers[0];
if (trigger) {
event.preventDefault();
trigger.focus();
}
}}
>
<CommandInput data-ui-id={UI_SURFACE_IDS.commandPaletteSearch} value={query} onValueChange={setQuery} />
<CommandList data-ui-id={UI_SURFACE_IDS.commandPaletteResults}>
<CommandEmpty>{t("app.commands.empty.title")}</CommandEmpty>
{canUseGlobalSearch ? (
<div className="flex flex-wrap gap-1.5 border-b border-border-neutral px-2 py-2">
{globalSearchEntityTypes.map((type) => {
const active = selectedEntityTypes.includes(type);
return (
<button
key={type}
type="button"
aria-pressed={active}
className={
active
? "rounded-md bg-neutral-900 px-2 py-1 text-xs font-medium text-white"
: "text-text-neutral-secondary rounded-md border border-border-neutral px-2 py-1 text-xs font-medium hover:bg-neutral-50"
}
onMouseDown={(event) => event.preventDefault()}
onClick={() => {
setSelectedEntityTypes((current) => {
if (current.includes(type)) {
const next = current.filter((entry) => entry !== type);
return next.length > 0 ? next : current;
}
return [...current, type];
});
}}
>
{t(`search.entities.${type}`)}
</button>
);
})}
</div>
) : null}
{canUseGlobalSearch && searchResults.length > 0 ? (
<CommandGroup heading={t("search.command.group")}>
{searchResults.map((result) => (
<CommandItem
key={`${result.entityType}:${result.id}`}
data-ui-id={UI_SURFACE_IDS.commandPaletteRow}
value={[result.title, result.subtitle, result.entityType].filter(Boolean).join(" ")}
onSelect={() => {
navigate(result.href);
setOpen(false);
}}
>
<div className="flex w-full items-center justify-between gap-2">
<div className="min-w-0">
<div className="text-text-neutral-primary/80 truncate text-sm font-medium">{highlightMatch(result.title, trimmedQuery)}</div>
<div className="text-text-neutral-tertiary truncate text-xs">{highlightMatch(result.subtitle, trimmedQuery)}</div>
</div>
<div className="text-text-neutral-tertiary shrink-0 text-xs">{t(`search.entities.${result.entityType}`)}</div>
</div>
</CommandItem>
))}
<CommandItem
data-ui-id={UI_SURFACE_IDS.commandPaletteRow}
value={`${t("search.command.allResults")} ${query}`}
onSelect={() => {
navigate(allResultsHref);
setOpen(false);
}}
>
<div className="text-text-neutral-primary/80 text-sm font-medium">{t("search.command.allResults", { count: searchResults.length })}</div>
</CommandItem>
</CommandGroup>
) : null}
{canUseGlobalSearch && trimmedQuery.length < 2 && recentSearches.length > 0 ? (
<CommandGroup heading={t("search.command.recent")}>
{recentSearches.map((recent) => (
<CommandItem
key={recent.id}
data-ui-id={UI_SURFACE_IDS.commandPaletteRow}
value={recent.queryText}
onSelect={() => {
setQuery(recent.queryText);
}}
>
<div className="flex w-full items-center justify-between gap-2">
<span className="text-text-neutral-primary/80 truncate text-sm font-medium">{recent.queryText}</span>
<span className="text-text-neutral-tertiary shrink-0 text-xs">{t("search.results.title", { count: recent.resultCount })}</span>
</div>
</CommandItem>
))}
</CommandGroup>
) : null}
<CommandGroup>
{resolvedActions.map((action) => (
<CommandItem
key={action.id}
data-ui-id={UI_SURFACE_IDS.commandPaletteRow}
value={[action.name, action.subtitle, action.keywords, action.id].filter(Boolean).join(" ")}
onSelect={() => {
action.perform?.(action);
setOpen(false);
}}
>
<div className="flex w-full items-center justify-between gap-2">
<div className="text-text-neutral-primary/80 text-sm font-medium">{action.name}</div>
{action.subtitle ? <div className="text-text-neutral-tertiary truncate text-xs">{action.subtitle}</div> : null}
</div>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</CommandDialog>
</div>
},
}}
/>
);
}
function highlightMatch(value: string, query: string) {
if (!query) return value;
const index = value.toLocaleLowerCase().indexOf(query.toLocaleLowerCase());
if (index < 0) return value;
const before = value.slice(0, index);
const match = value.slice(index, index + query.length);
const after = value.slice(index + query.length);
return (
<>
{before}
<mark className="rounded bg-yellow-100 px-0.5 text-inherit">{match}</mark>
{after}
</>
);
function isGlobalSearchResponse(value: SearchFetcherData | undefined): value is GlobalSearchResponse {
return !!value && "results" in value && "requestKey" in value;
}
@@ -0,0 +1,394 @@
import { useTranslation } from "react-i18next";
import {
FeatherBuilding2,
FeatherCheckSquare,
FeatherChevronDown,
FeatherClock,
FeatherFile,
FeatherFolder,
FeatherLoader,
FeatherSearch,
FeatherShield,
FeatherTrendingUp,
FeatherUser,
FeatherUsers,
} from "@subframe/core";
import {
SPOTLIGHT_SEARCH_ENTITY_ORDER,
type SpotlightSearchDialogVM,
type SpotlightSearchEntityType,
type SpotlightSearchItemVM,
type SpotlightSearchRecentVM,
} from "@hivegrid/view-models";
import {
UI_ACTION_IDS,
UI_ID_PATTERNS,
UI_SURFACE_IDS,
getCommandPaletteActionId,
getCommandPaletteRecentId,
getCommandPaletteResultId,
} from "~/application/ui/uiRegistry";
import { CommandDialog, CommandGroup, CommandInput, CommandItem, CommandList } from "~/components/ui/command";
import {
ArrowLeftRightIcon,
ChevronRightIcon,
CodeIcon,
CreditCard,
FileTextIcon,
HomeIcon,
LogOut,
PlusIcon,
ShieldCheckIcon,
StoreIcon,
UserIcon,
} from "~/components/ui/icons/vendor";
import { useLocaleFormatters } from "~/locale/format";
import { BadgeShortcut } from "~/ui/components/BadgeShortcut";
import { Button } from "~/ui/components/Button";
import { IconWithBackground } from "~/ui/components/IconWithBackground";
export type SpotlightSearchDialogActions = {
readonly onOpenChange: (open: boolean) => void;
readonly onQueryChange: (query: string) => void;
readonly onToggleEntityType: (entityType: SpotlightSearchEntityType) => void;
readonly onSelectRecent: (recent: SpotlightSearchRecentVM) => void;
readonly onPrepareResultSelection: () => void;
readonly onSelectResult: (item: SpotlightSearchItemVM) => void;
readonly onLoadMore: () => void;
readonly onRetry: () => void;
readonly onSelectAction: (actionId: string) => void;
readonly onCommandKeyDownCapture: React.KeyboardEventHandler<HTMLDivElement>;
readonly onCloseAutoFocus: (event: Event) => void;
};
/** Presentational AD-28 interim UI. Data and side effects enter only through vm/actions. */
export function SpotlightSearchDialogView({ vm, actions }: { vm: SpotlightSearchDialogVM; actions: SpotlightSearchDialogActions }) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
return (
<CommandDialog
open={vm.open}
onOpenChange={actions.onOpenChange}
dataUiId={UI_SURFACE_IDS.commandPalettePortal}
shouldFilter={false}
onCommandKeyDownCapture={actions.onCommandKeyDownCapture}
onCloseAutoFocus={actions.onCloseAutoFocus}
>
<CommandInput
data-ui-id={UI_SURFACE_IDS.commandPaletteSearch}
value={vm.query}
onValueChange={actions.onQueryChange}
placeholder={t("search.command.placeholder")}
aria-label={t("search.form.label")}
/>
{vm.canUseGlobalSearch ? (
<div
className="border-border-default flex flex-nowrap gap-1 overflow-x-auto border-b px-3 py-2 [scrollbar-width:none] sm:px-4 [&::-webkit-scrollbar]:hidden"
data-ui-id={UI_SURFACE_IDS.commandPaletteFilters}
aria-label={t("search.command.filters")}
>
{SPOTLIGHT_SEARCH_ENTITY_ORDER.map((entityType) => {
const active = vm.selectedEntityTypes.includes(entityType);
return (
<button
key={entityType}
type="button"
aria-pressed={active}
className={
active
? "bg-surface-feedback-solid-neutral text-body-extra-small-medium-0 font-body-extra-small-medium-0 text-text-neutral-on-solid shrink-0 rounded-md px-2.5 py-1 transition-colors"
: "border-border-default bg-surface-neutral-primary text-body-extra-small-medium-0 font-body-extra-small-medium-0 text-text-neutral-secondary hover:bg-surface-neutral-secondary shrink-0 rounded-md border px-2.5 py-1 transition-colors"
}
onMouseDown={(event) => event.preventDefault()}
onClick={() => actions.onToggleEntityType(entityType)}
>
{t(`search.entities.${entityType}`)}
</button>
);
})}
</div>
) : null}
<CommandList data-ui-id={UI_SURFACE_IDS.commandPaletteResults} className="max-h-none flex-1 pb-2 sm:max-h-[min(52vh,30rem)] sm:flex-none">
{vm.canUseGlobalSearch && !vm.isSearchQuery ? (
<SearchStatus icon={<FeatherSearch />} dataUiId={UI_SURFACE_IDS.commandPaletteQueryHint}>
{t("search.command.minimumCharacters")}
</SearchStatus>
) : null}
{vm.canUseGlobalSearch && vm.isSearchQuery && vm.searchState === "loading" ? (
<SearchStatus icon={<FeatherLoader className="animate-spin" />} dataUiId={UI_SURFACE_IDS.commandPaletteSearchStatus} live>
{t("search.command.loading")}
</SearchStatus>
) : null}
{vm.canUseGlobalSearch && vm.isSearchQuery && vm.searchState === "error" ? (
<SearchStatus icon={<FeatherSearch />} dataUiId={UI_SURFACE_IDS.commandPaletteSearchStatus} live>
<span className="flex flex-col items-center gap-2">
<span>{t("search.command.error")}</span>
<Button variant="tertiary" size="small" onMouseDown={(event) => event.preventDefault()} onClick={actions.onRetry}>
{t("shared.retry")}
</Button>
</span>
</SearchStatus>
) : null}
{vm.canUseGlobalSearch && vm.isSearchQuery && vm.searchState === "empty" ? (
<SearchStatus icon={<FeatherSearch />} dataUiId={UI_SURFACE_IDS.commandPaletteSearchStatus} live>
{t("search.results.empty")}
</SearchStatus>
) : null}
{vm.canUseGlobalSearch && !vm.isSearchQuery && vm.searchState !== "loading" && vm.recentSearches.length > 0 ? (
<CommandGroup heading={t("search.command.recent")}>
{vm.recentSearches.map((recent) => (
<CommandItem
key={recent.id}
data-ui-id={getCommandPaletteRecentId(recent.id)}
data-ui-id-pattern={UI_ID_PATTERNS.commandPaletteRecent}
data-ui-id-param-recentid={recent.id}
value={recent.queryText}
onSelect={() => actions.onSelectRecent(recent)}
>
<IconWithBackground variant="secondary" size="small" icon={<FeatherClock />} className="size-8 shrink-0" />
<div className="min-w-0 grow">
<div className="text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-primary truncate">{recent.queryText}</div>
<div className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t("search.results.title", { count: recent.resultCount })}
</div>
</div>
</CommandItem>
))}
</CommandGroup>
) : null}
{vm.canUseGlobalSearch && !vm.isSearchQuery && vm.searchState !== "loading" && vm.hasResolvedResponse && vm.recentSearches.length === 0 ? (
<SearchStatus icon={<FeatherClock />} dataUiId={UI_SURFACE_IDS.commandPaletteRecentStatus}>
{t("search.recent.empty")}
</SearchStatus>
) : null}
{vm.canUseGlobalSearch && vm.isSearchQuery && vm.searchState !== "error"
? vm.searchGroups.map((group) => (
<CommandGroup key={group.entityType} heading={t(group.labelKey)}>
{group.items.map((item) => (
<CommandItem
key={item.key}
data-ui-id={getCommandPaletteResultId(item.entityType, item.id)}
data-ui-id-pattern={UI_ID_PATTERNS.commandPaletteResult}
data-ui-id-param-entitytype={item.entityType}
data-ui-id-param-entityid={item.id}
value={item.searchValue}
onPointerDownCapture={actions.onPrepareResultSelection}
onSelect={() => actions.onSelectResult(item)}
>
<IconWithBackground variant="secondary" size="small" icon={entityIcon(item.entityType)} className="size-9 shrink-0" />
<div className="min-w-0 grow">
<div className="text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-primary truncate">
{highlightMatch(item.title, vm.query.trim())}
</div>
{item.subtitle ? (
<div className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary truncate">
{highlightMatch(item.subtitle, vm.query.trim())}
</div>
) : null}
</div>
{item.updatedAt ? (
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary hidden shrink-0 sm:inline">
{formatters.relativeDate(item.updatedAt)}
</span>
) : null}
</CommandItem>
))}
</CommandGroup>
))
: null}
{vm.canLoadMore ? (
<div className="flex justify-center px-4 py-2">
<Button
variant="tertiary"
size="small"
iconRight={<FeatherChevronDown />}
data-ui-id={UI_ACTION_IDS.commandPaletteLoadMore}
onMouseDown={(event) => event.preventDefault()}
onClick={actions.onLoadMore}
>
{t("search.command.loadMore")}
</Button>
</div>
) : null}
{vm.canUseGlobalSearch && vm.isSearchQuery && vm.searchState !== "loading" && vm.hiddenEntityTypes.length > 0 ? (
<SearchStatus icon={<FeatherShield />} dataUiId={UI_SURFACE_IDS.commandPalettePermissionHint} subtle>
{t("search.results.hidden", {
entities: vm.hiddenEntityTypes.map((type) => t(`search.entities.${type}`)).join(", "),
})}
</SearchStatus>
) : null}
{vm.visibleActions.length > 0 ? (
<CommandGroup heading={t(vm.isSearchQuery ? "search.command.actions" : "search.command.quickAccess")}>
{vm.visibleActions.map((action) => (
<CommandItem key={action.id} {...commandActionUiIdAttrs(action.id)} value={action.searchValue} onSelect={() => actions.onSelectAction(action.id)}>
<div className="flex w-full min-w-0 items-center gap-2">
<IconWithBackground
data-slot="command-action-icon"
variant="neutral"
size="small"
icon={getActionIcon(action.id)}
className="size-7 shrink-0 p-1.5"
/>
<div className="text-text-neutral-secondary text-body-small-medium-150 font-body-small-medium-150 min-w-0 grow truncate">{action.name}</div>
{action.subtitle ? (
<div className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary hidden max-w-40 truncate sm:block">
{action.subtitle}
</div>
) : null}
<ChevronRightIcon className="text-icon-neutral-tertiary size-4 shrink-0 opacity-0 transition-opacity group-data-[selected=true]/command-item:opacity-100" />
</div>
</CommandItem>
))}
</CommandGroup>
) : null}
{!vm.canUseGlobalSearch && vm.visibleActions.length === 0 ? (
<SearchStatus icon={<FeatherSearch />} dataUiId={UI_SURFACE_IDS.commandPaletteSearchStatus}>
{t("app.commands.empty.title")}
</SearchStatus>
) : null}
</CommandList>
<div
className="border-border-default bg-surface-neutral-secondary text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary flex items-center justify-between gap-2 border-t px-3 py-2 sm:px-4"
data-ui-id={UI_SURFACE_IDS.commandPaletteFooter}
>
<span className="flex items-center gap-1.5">
<BadgeShortcut icon={null} size="small">
↑↓
</BadgeShortcut>
<span className="hidden sm:inline">{t("search.command.navigate")}</span>
</span>
<span className="flex items-center gap-1.5">
<BadgeShortcut icon={null} size="small">
↵
</BadgeShortcut>
<span>{t("search.command.open")}</span>
</span>
<span className="flex items-center gap-1.5">
<BadgeShortcut icon={null} size="small">
⌘↵
</BadgeShortcut>
<span className="hidden sm:inline">{t("search.command.openNewTab")}</span>
</span>
</div>
</CommandDialog>
);
}
function commandActionUiIdAttrs(actionId: string) {
return {
"data-ui-id": getCommandPaletteActionId(actionId),
"data-ui-id-pattern": UI_ID_PATTERNS.commandPaletteAction,
"data-ui-id-param-actionid": actionId,
};
}
function getActionIcon(actionId: string) {
switch (actionId) {
case "dashboard":
case "registry-dashboard":
return <HomeIcon />;
case "profile":
case "members":
return <UserIcon />;
case "subscription":
return <CreditCard />;
case "account":
return <StoreIcon />;
case "apiKeys":
return <CodeIcon />;
case "auditTrails":
case "events":
return <FileTextIcon />;
case "switch account":
return <ArrowLeftRightIcon />;
case "create account":
return <PlusIcon />;
case "switch to admin":
return <ShieldCheckIcon />;
case "logout":
return <LogOut />;
default:
return <ChevronRightIcon />;
}
}
function SearchStatus({
children,
icon,
dataUiId,
live = false,
subtle = false,
}: {
children: React.ReactNode;
icon: React.ReactNode;
dataUiId: string;
live?: boolean;
subtle?: boolean;
}) {
return (
<CommandItem disabled value={`status:${dataUiId}`} className="cursor-default p-0 data-[disabled=true]:opacity-100" data-ui-id={dataUiId}>
<div
className={
subtle
? "bg-surface-neutral-secondary text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary mx-3 my-2 flex w-full items-center gap-2 rounded-md px-3 py-2 sm:mx-4"
: "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary flex w-full items-center justify-center gap-2 px-4 py-5 text-center"
}
role={live ? "status" : undefined}
aria-live={live ? "polite" : undefined}
>
<span className="text-icon-neutral-tertiary shrink-0">{icon}</span>
<span>{children}</span>
</div>
</CommandItem>
);
}
function entityIcon(entityType: SpotlightSearchEntityType) {
switch (entityType) {
case "contact":
return <FeatherUser />;
case "company":
return <FeatherBuilding2 />;
case "lead":
return <FeatherTrendingUp />;
case "project":
return <FeatherFolder />;
case "file":
return <FeatherFile />;
case "task":
return <FeatherCheckSquare />;
case "employee":
return <FeatherUsers />;
case "user":
return <FeatherUsers />;
}
}
function highlightMatch(value: string, query: string) {
if (!query) return value;
const index = value.toLocaleLowerCase().indexOf(query.toLocaleLowerCase());
if (index < 0) return value;
const before = value.slice(0, index);
const match = value.slice(index, index + query.length);
const after = value.slice(index + query.length);
return (
<>
{before}
<mark className="bg-surface-feedback-subtle-warning rounded-sm px-0.5 text-inherit">{match}</mark>
{after}
</>
);
}
@@ -0,0 +1,119 @@
import { useMemo } from "react";
import { createMemoryRouter, Outlet, RouterProvider } from "react-router";
import CommandPaletteDialog from "./CommandPaletteDialog";
const rootData = {
csrf: "visual-csrf",
appConfiguration: { app: { features: {} } },
};
const appData = {
currentTenant: { id: "tenant-1", slug: "acme", name: "HiveGrid Demo" },
permissions: ["search.use", "crm.read_all", "projects.read_all"],
user: { id: "user-1", email: "visual@example.test", firstName: "Visual", lastName: "Fixture" },
myTenants: [],
allRoles: [],
myGroups: [],
isSuperUser: false,
isSuperAdmin: false,
onboardingSession: null,
};
/** Deterministic real-component fixture for the R-P11a interim pixel baseline. */
export function SpotlightSearchVisualFixture() {
const router = useMemo(
() =>
createMemoryRouter(
[
{
id: "root",
path: "/",
loader: () => rootData,
element: <Outlet />,
children: [
{
id: "routes/app.$tenant",
path: ":tenant",
loader: () => appData,
element: <Outlet />,
children: [
{
index: true,
element: <CommandPaletteDialog actions={[]} layout="app" open setOpen={() => undefined} />,
},
{
path: "search/api",
loader: ({ request }) => buildSearchResponse(request),
},
],
},
],
},
],
{ initialEntries: ["/acme"] }
),
[]
);
return <RouterProvider router={router} />;
}
function buildSearchResponse(request: Request) {
const url = new URL(request.url);
const query = url.searchParams.get("q")?.trim() ?? "";
const requestedEntityTypes = url.searchParams.getAll("type");
const limit = Number(url.searchParams.get("limit") ?? 20);
const requestId = url.searchParams.get("requestId");
return {
query,
requestedEntityTypes,
requestId,
requestKey: `${encodeURIComponent(query)}|${requestedEntityTypes.join(",") || "*"}|${limit}`,
results: query
? [
{
id: "contact-1",
entityType: "contact",
title: "Solaris GmbH",
subtitle: "info@solaris.test",
href: "/acme/contacts/contact-1",
permissionSubject: "crm.read_all",
updatedAt: null,
},
{
id: "project-1",
entityType: "project",
title: "Solardach Musterstraße",
subtitle: "P-100",
href: "/acme/projects/project-1",
permissionSubject: "projects.read_all",
updatedAt: null,
},
]
: [],
recentSearches: query
? []
: [
{
id: "recent-1",
queryText: "Wärmepumpe",
entityTypes: ["project", "task"],
resultCount: 4,
createdAt: "2026-07-12T08:00:00.000Z",
},
],
hiddenEntityTypes: ["lead", "file", "task", "user"],
latencyHint: "Suchindex-Aktualisierungen können bis zu 10 Sekunden dauern.",
} satisfies {
query: string;
requestedEntityTypes: string[];
requestId: string | null;
requestKey: string;
results: unknown[];
recentSearches: unknown[];
hiddenEntityTypes: string[];
latencyHint: string;
};
}