import { useEffect, useMemo, 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 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"; const globalSearchEntityTypes: GlobalSearchEntityType[] = ["contact", "company", "lead", "project", "file", "task", "user"]; export default function CommandPaletteDialog({ actions, layout, open, setOpen, }: { actions?: ScopedCommandAction[]; layout?: CommandRegistryLayout; open: boolean; setOpen: (open: boolean) => void; }) { const { t, i18n } = useTranslation(); const navigate = useNavigate(); const fetcher = useFetcher(); const searchFetcher = useFetcher(); const appData = useAppOrAdminData() as AppLoaderData | undefined; const rootData = useRootData(); const [query, setQuery] = useState(""); const [selectedEntityTypes, setSelectedEntityTypes] = useState(globalSearchEntityTypes); 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]); 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" })); return; } const typeSuffix = activeTypeParams ? `&${activeTypeParams}` : ""; const timeout = window.setTimeout(() => { searchFetcher.load(appPath({ tenantSlug: appData.currentTenant.slug, path: `search/api?q=${encodeURIComponent(trimmedQuery)}&limit=6${typeSuffix}`, mode: "host-aware" })); }, 300); return () => window.clearTimeout(timeout); }, [activeTypeParams, appData?.currentTenant?.slug, canUseGlobalSearch, open, searchFetcher, trimmedQuery]); const resolvedActions = actions ?? (layout ? getCommandRegistryActions({ layout, t, i18n, navigate, submitLogout: () => { const form = new FormData(); if (rootData?.csrf) { form.set("csrf", rootData.csrf); } fetcher.submit(form, { method: "post", action: "/logout" }); }, appData, rootData, }) : []); return (
{ // The palette opens via controlled state, not a Radix trigger, so Radix // drops focus to on close. Return focus to the search trigger. const trigger = typeof document !== "undefined" ? document.querySelector('[data-ui-id="ui.action.shell.search"]') : null; if (trigger) { event.preventDefault(); trigger.focus(); } }} > {t("app.commands.empty.title")} {canUseGlobalSearch ? (
{globalSearchEntityTypes.map((type) => { const active = selectedEntityTypes.includes(type); return ( ); })}
) : null} {canUseGlobalSearch && searchResults.length > 0 ? ( {searchResults.map((result) => ( { navigate(result.href); setOpen(false); }} >
{highlightMatch(result.title, trimmedQuery)}
{highlightMatch(result.subtitle, trimmedQuery)}
{t(`search.entities.${result.entityType}`)}
))} { navigate(allResultsHref); setOpen(false); }} >
{t("search.command.allResults", { count: searchResults.length })}
) : null} {canUseGlobalSearch && trimmedQuery.length < 2 && recentSearches.length > 0 ? ( {recentSearches.map((recent) => ( { setQuery(recent.queryText); }} >
{recent.queryText} {t("search.results.title", { count: recent.resultCount })}
))}
) : null} {resolvedActions.map((action) => ( { action.perform?.(action); setOpen(false); }} >
{action.name}
{action.subtitle ?
{action.subtitle}
: null}
))}
); } 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} {match} {after} ); }