Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/components/ui/commandPalettes/CommandPaletteDialog.tsx
T
2026-07-08 16:15:37 +02:00

219 lines
9.9 KiB
TypeScript

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<GlobalSearchResponse>();
const appData = useAppOrAdminData() as AppLoaderData | undefined;
const rootData = useRootData();
const [query, setQuery] = useState("");
const [selectedEntityTypes, setSelectedEntityTypes] = useState<GlobalSearchEntityType[]>(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 (
<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;
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}
</>
);
}