Skip to content

A full-featured CRM built with React, shadcn/ui, and Supabase.

Colocate the global search code in two files

François Zaninotto66628125e927
diff --git a/registry.json b/registry.json
index 0b9c2f61..3aa006d2 100644
--- a/registry.json
+++ b/registry.json
@@ -162,27 +162,7 @@
"type": "registry:component"
},
{
- "path": "src/components/atomic-crm/search/useGlobalSearch.ts",
- "type": "registry:component"
- },
- {
- "path": "src/components/atomic-crm/search/searchResources.ts",
- "type": "registry:component"
- },
- {
- "path": "src/components/atomic-crm/search/searchHighlight.ts",
- "type": "registry:component"
- },
- {
- "path": "src/components/atomic-crm/search/index.ts",
- "type": "registry:component"
- },
- {
- "path": "src/components/atomic-crm/search/getSearchResultUrl.ts",
- "type": "registry:component"
- },
- {
- "path": "src/components/atomic-crm/search/GlobalSearchDialog.tsx",
+ "path": "src/components/atomic-crm/search/searchModel.ts",
"type": "registry:component"
},
{
diff --git a/src/components/atomic-crm/layout/Header.tsx b/src/components/atomic-crm/layout/Header.tsx
index 80e130df..c8721aed 100644
--- a/src/components/atomic-crm/layout/Header.tsx
+++ b/src/components/atomic-crm/layout/Header.tsx
@@ -9,7 +9,7 @@ import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { useConfigurationContext } from "../root/ConfigurationContext";
import { ImportPage } from "../misc/ImportPage";
import { ChangelogPage } from "../misc/ChangelogPage";
-import { GlobalSearchButton } from "../search";
+import { GlobalSearchButton } from "../search/GlobalSearchButton";
const Header = () => {
const { darkModeLogo, lightModeLogo, title } = useConfigurationContext();
diff --git a/src/components/atomic-crm/layout/MobileHeader.tsx b/src/components/atomic-crm/layout/MobileHeader.tsx
index a3efd81e..4d325272 100644
--- a/src/components/atomic-crm/layout/MobileHeader.tsx
+++ b/src/components/atomic-crm/layout/MobileHeader.tsx
@@ -1,4 +1,4 @@
-import { GlobalSearchButton } from "../search";
+import { GlobalSearchButton } from "../search/GlobalSearchButton";
import { MobileRefreshButton } from "./MobileRefreshButton";
// The search lives here rather than in each screen: there is no Cmd+K on a
diff --git a/src/components/atomic-crm/providers/fakerest/search.ts b/src/components/atomic-crm/providers/fakerest/search.ts
index 2ef7d7d9..bf5a59b4 100644
--- a/src/components/atomic-crm/providers/fakerest/search.ts
+++ b/src/components/atomic-crm/providers/fakerest/search.ts
@@ -10,8 +10,11 @@ import type {
SearchResult,
Task,
} from "../../types";
-import { getSearchTerms, matchesAllTerms } from "../../search/searchHighlight";
-import { DESKTOP_SEARCH_RESOURCES } from "../../search/searchResources";
+import {
+ DESKTOP_SEARCH_RESOURCES,
+ getSearchTerms,
+ matchesAllTerms,
+} from "../../search/searchModel";
const DEFAULT_MAX_RESULTS = 50;
const TITLE_LENGTH = 200;
diff --git a/src/components/atomic-crm/search/GlobalSearchDialog.test.tsx b/src/components/atomic-crm/search/GlobalSearchButton.test.tsx
similarity index 99%
rename from src/components/atomic-crm/search/GlobalSearchDialog.test.tsx
rename to src/components/atomic-crm/search/GlobalSearchButton.test.tsx
index 2e6b71a7..20ffb48a 100644
--- a/src/components/atomic-crm/search/GlobalSearchDialog.test.tsx
+++ b/src/components/atomic-crm/search/GlobalSearchButton.test.tsx
@@ -6,7 +6,7 @@ import { onlineManager } from "@tanstack/react-query";
import { StoryWrapper, buildContact } from "@/test/StoryWrapper";
-import { GlobalSearchDialog } from "./GlobalSearchDialog";
+import { GlobalSearchDialog } from "./GlobalSearchButton";
const PLACEHOLDER = "Search contacts, companies, deals, tasks and notes...";
diff --git a/src/components/atomic-crm/search/GlobalSearchButton.tsx b/src/components/atomic-crm/search/GlobalSearchButton.tsx
index fd13560a..3a37115c 100644
--- a/src/components/atomic-crm/search/GlobalSearchButton.tsx
+++ b/src/components/atomic-crm/search/GlobalSearchButton.tsx
@@ -1,10 +1,39 @@
+import { useQuery } from "@tanstack/react-query";
import { Search } from "lucide-react";
-import { useTranslate } from "ra-core";
-import { useEffect, useState } from "react";
+import { useDataProvider, useTranslate } from "ra-core";
+import { useEffect, useMemo, useState } from "react";
+import { useNavigate } from "react-router";
import { Button } from "@/components/ui/button";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from "@/components/ui/command";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { useIsMobile } from "@/hooks/use-mobile";
+import { cn } from "@/lib/utils";
-import { GlobalSearchDialog } from "./GlobalSearchDialog";
+import type { CrmDataProvider } from "../providers/types";
+import type { SearchResourceName, SearchResult } from "../types";
+import {
+ DESKTOP_SEARCH_RESOURCES,
+ MOBILE_SEARCH_RESOURCES,
+ SEARCH_RESOURCES,
+ getSearchResultUrl,
+ getSearchTerms,
+ getSnippet,
+ highlight,
+} from "./searchModel";
// Whether the keyboard shortcut fired while the user is typing in a field, in
// which case it must not open the dialog. contenteditable covers rich text
@@ -92,3 +121,251 @@ export const GlobalSearchButton = ({
</>
);
};
+
+const MIN_SEARCH_LENGTH = 2;
+const DEBOUNCE_MS = 300;
+const MAX_RESULTS = 50;
+
+const useDebouncedValue = <T,>(value: T, delay: number): T => {
+ const [debouncedValue, setDebouncedValue] = useState(value);
+
+ useEffect(() => {
+ const timeout = setTimeout(() => setDebouncedValue(value), delay);
+ return () => clearTimeout(timeout);
+ }, [value, delay]);
+
+ return debouncedValue;
+};
+
+/**
+ * Run the global search for a debounced search term.
+ *
+ * Stays idle until the term reaches MIN_SEARCH_LENGTH, so opening the dialog
+ * does not fire a request. `resources` restricts the query server-side, so the
+ * row cap is spent only on resources the current layout can actually link to.
+ */
+const useGlobalSearch = (
+ query: string,
+ resources: readonly SearchResourceName[],
+) => {
+ const dataProvider = useDataProvider<CrmDataProvider>();
+ const debouncedQuery = useDebouncedValue(query.trim(), DEBOUNCE_MS);
+ const isEnabled = debouncedQuery.length >= MIN_SEARCH_LENGTH;
+
+ const { data, isPending, error } = useQuery({
+ queryKey: ["globalSearch", debouncedQuery, resources],
+ queryFn: () =>
+ dataProvider.globalSearch(debouncedQuery, resources, MAX_RESULTS),
+ enabled: isEnabled,
+ meta: { persist: false },
+ // offlineFirst (the app default) pauses a failed search while offline,
+ // leaving the dialog loading forever instead of reporting the error
+ networkMode: "always",
+ });
+
+ return {
+ results: isEnabled ? (data ?? []) : [],
+ isPending: isEnabled && isPending,
+ error,
+ debouncedQuery,
+ };
+};
+
+type LinkedResult = { result: SearchResult; url: string };
+
+// A title-line excerpt must keep the match on screen, so less lead-in text.
+const TITLE_SNIPPET_RADIUS = 25;
+
+const Highlighted = ({ text, terms }: { text: string; terms: string[] }) =>
+ highlight(text, terms).map((part, index) =>
+ part.isMatch ? (
+ <mark
+ key={index}
+ className="rounded-sm bg-yellow-200 text-inherit dark:bg-yellow-400/30"
+ >
+ {part.text}
+ </mark>
+ ) : (
+ part.text
+ ),
+ );
+
+export const GlobalSearchDialog = ({
+ open,
+ onOpenChange,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) => {
+ const translate = useTranslate();
+ const navigate = useNavigate();
+ const isMobile = useIsMobile();
+ const [query, setQuery] = useState("");
+ const { results, isPending, error, debouncedQuery } = useGlobalSearch(
+ query,
+ isMobile ? MOBILE_SEARCH_RESOURCES : DESKTOP_SEARCH_RESOURCES,
+ );
+
+ // Resources are already scoped to this layout server-side; this only drops
+ // the rare row whose parent record is missing.
+ const linkedResults = useMemo(
+ () =>
+ results.reduce<LinkedResult[]>((acc, result) => {
+ const url = getSearchResultUrl(result, isMobile);
+ return url ? [...acc, { result, url }] : acc;
+ }, []),
+ [results, isMobile],
+ );
+
+ const handleOpenChange = (nextOpen: boolean) => {
+ if (!nextOpen) {
+ setQuery("");
+ }
+ onOpenChange(nextOpen);
+ };
+
+ const handleSelect = (url: string) => {
+ handleOpenChange(false);
+ navigate(url);
+ };
+
+ const isTooShort = debouncedQuery.length < MIN_SEARCH_LENGTH;
+ const terms = useMemo(() => getSearchTerms(debouncedQuery), [debouncedQuery]);
+
+ return (
+ <Dialog open={open} onOpenChange={handleOpenChange}>
+ {/* Desktop: pinned near the top so the box grows downwards as results
+ arrive instead of re-centering on every keystroke. Mobile: the whole
+ screen. */}
+ <DialogContent
+ className={cn(
+ "overflow-hidden p-0",
+ isMobile
+ ? "inset-0 h-dvh max-w-none translate-x-0 translate-y-0 grid-rows-[minmax(0,1fr)] rounded-none border-0 sm:max-w-none"
+ : "top-[12vh] translate-y-0 sm:max-w-xl",
+ )}
+ >
+ {/* inside the content, so nothing renders while the dialog is closed */}
+ <DialogHeader className="sr-only">
+ <DialogTitle>{translate("crm.search.title")}</DialogTitle>
+ <DialogDescription>
+ {translate("crm.search.placeholder")}
+ </DialogDescription>
+ </DialogHeader>
+ {/* results come from the server, already filtered; same look as
+ shadcn's CommandDialog, which this composes from Dialog and Command
+ itself to control the layout and filtering */}
+ <Command
+ shouldFilter={false}
+ 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"
+ >
+ <CommandInput
+ placeholder={translate("crm.search.placeholder")}
+ value={query}
+ onValueChange={setQuery}
+ // keep the text clear of the dialog's close button, drawn over the
+ // input's right end
+ className="pr-8"
+ />
+ <CommandList
+ className={isMobile ? "max-h-none flex-1" : "max-h-[60vh]"}
+ >
+ {isTooShort ? (
+ <div className="py-6 text-center text-sm text-muted-foreground">
+ {translate("crm.search.hint", { min: MIN_SEARCH_LENGTH })}
+ </div>
+ ) : error ? (
+ <div
+ role="alert"
+ className="py-6 text-center text-sm text-destructive"
+ >
+ {translate("crm.search.error")}
+ </div>
+ ) : isPending ? (
+ <div className="py-6 text-center text-sm text-muted-foreground">
+ {translate("crm.common.loading")}
+ </div>
+ ) : (
+ <>
+ <CommandEmpty>{translate("crm.search.empty")}</CommandEmpty>
+ {SEARCH_RESOURCES.map(({ name, icon: Icon, labelKey }) => {
+ const groupResults = linkedResults.filter(
+ ({ result }) => result.resource === name,
+ );
+ if (groupResults.length === 0) {
+ return null;
+ }
+ return (
+ <CommandGroup key={name} heading={translate(labelKey)}>
+ {groupResults.map(({ result, url }) => {
+ const title =
+ result.title ||
+ translate("crm.search.untitled_result");
+ // A note's or task's title is the start of its text: when
+ // the match is further in, show the text around it instead.
+ const isTitleFromContent =
+ !!result.content && result.content.startsWith(title);
+ const snippet = result.content
+ ? getSnippet(
+ title,
+ result.content,
+ terms,
+ isTitleFromContent
+ ? TITLE_SNIPPET_RADIUS
+ : undefined,
+ )
+ : null;
+ const displayedTitle =
+ isTitleFromContent && snippet ? snippet : title;
+ const secondLine = isTitleFromContent ? null : snippet;
+ return (
+ <CommandItem
+ key={`${result.resource}.${result.record_id}`}
+ value={`${result.resource}.${result.record_id}`}
+ onSelect={() => handleSelect(url)}
+ className="items-start"
+ >
+ <Icon className="mt-0.5 shrink-0" />
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <div className="flex items-baseline gap-2">
+ <span
+ className={
+ isTitleFromContent
+ ? "line-clamp-2"
+ : "truncate"
+ }
+ >
+ <Highlighted
+ text={displayedTitle}
+ terms={terms}
+ />
+ </span>
+ {result.subtitle ? (
+ <span className="ml-auto shrink-0 text-xs text-muted-foreground">
+ {result.subtitle}
+ </span>
+ ) : null}
+ </div>
+ {secondLine ? (
+ <span className="line-clamp-2 text-xs text-muted-foreground">
+ <Highlighted
+ text={secondLine}
+ terms={terms}
+ />
+ </span>
+ ) : null}
+ </div>
+ </CommandItem>
+ );
+ })}
+ </CommandGroup>
+ );
+ })}
+ </>
+ )}
+ </CommandList>
+ </Command>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/src/components/atomic-crm/search/GlobalSearchDialog.tsx b/src/components/atomic-crm/search/GlobalSearchDialog.tsx
deleted file mode 100644
index ec41d805..00000000
--- a/src/components/atomic-crm/search/GlobalSearchDialog.tsx
+++ /dev/null
@@ -1,230 +0,0 @@
-import { useTranslate } from "ra-core";
-import { useMemo, useState } from "react";
-import { useNavigate } from "react-router";
-
-import {
- Command,
- CommandEmpty,
- CommandGroup,
- CommandInput,
- CommandItem,
- CommandList,
-} from "@/components/ui/command";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import { useIsMobile } from "@/hooks/use-mobile";
-import { cn } from "@/lib/utils";
-
-import type { SearchResult } from "../types";
-import { getSearchResultUrl } from "./getSearchResultUrl";
-import { getSearchTerms, getSnippet, highlight } from "./searchHighlight";
-import {
- DESKTOP_SEARCH_RESOURCES,
- MOBILE_SEARCH_RESOURCES,
- SEARCH_RESOURCES,
-} from "./searchResources";
-import { MIN_SEARCH_LENGTH, useGlobalSearch } from "./useGlobalSearch";
-
-type LinkedResult = { result: SearchResult; url: string };
-
-// A title-line excerpt must keep the match on screen, so less lead-in text.
-const TITLE_SNIPPET_RADIUS = 25;
-
-const Highlighted = ({ text, terms }: { text: string; terms: string[] }) =>
- highlight(text, terms).map((part, index) =>
- part.isMatch ? (
- <mark
- key={index}
- className="rounded-sm bg-yellow-200 text-inherit dark:bg-yellow-400/30"
- >
- {part.text}
- </mark>
- ) : (
- part.text
- ),
- );
-
-export const GlobalSearchDialog = ({
- open,
- onOpenChange,
-}: {
- open: boolean;
- onOpenChange: (open: boolean) => void;
-}) => {
- const translate = useTranslate();
- const navigate = useNavigate();
- const isMobile = useIsMobile();
- const [query, setQuery] = useState("");
- const { results, isPending, error, debouncedQuery } = useGlobalSearch(
- query,
- isMobile ? MOBILE_SEARCH_RESOURCES : DESKTOP_SEARCH_RESOURCES,
- );
-
- // Resources are already scoped to this layout server-side; this only drops
- // the rare row whose parent record is missing.
- const linkedResults = useMemo(
- () =>
- results.reduce<LinkedResult[]>((acc, result) => {
- const url = getSearchResultUrl(result, isMobile);
- return url ? [...acc, { result, url }] : acc;
- }, []),
- [results, isMobile],
- );
-
- const handleOpenChange = (nextOpen: boolean) => {
- if (!nextOpen) {
- setQuery("");
- }
- onOpenChange(nextOpen);
- };
-
- const handleSelect = (url: string) => {
- handleOpenChange(false);
- navigate(url);
- };
-
- const isTooShort = debouncedQuery.length < MIN_SEARCH_LENGTH;
- const terms = useMemo(() => getSearchTerms(debouncedQuery), [debouncedQuery]);
-
- return (
- <Dialog open={open} onOpenChange={handleOpenChange}>
- {/* Desktop: pinned near the top so the box grows downwards as results
- arrive instead of re-centering on every keystroke. Mobile: the whole
- screen. */}
- <DialogContent
- className={cn(
- "overflow-hidden p-0",
- isMobile
- ? "inset-0 h-dvh max-w-none translate-x-0 translate-y-0 grid-rows-[minmax(0,1fr)] rounded-none border-0 sm:max-w-none"
- : "top-[12vh] translate-y-0 sm:max-w-xl",
- )}
- >
- {/* inside the content, so nothing renders while the dialog is closed */}
- <DialogHeader className="sr-only">
- <DialogTitle>{translate("crm.search.title")}</DialogTitle>
- <DialogDescription>
- {translate("crm.search.placeholder")}
- </DialogDescription>
- </DialogHeader>
- {/* results come from the server, already filtered; same look as
- shadcn's CommandDialog, which this composes from Dialog and Command
- itself to control the layout and filtering */}
- <Command
- shouldFilter={false}
- 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"
- >
- <CommandInput
- placeholder={translate("crm.search.placeholder")}
- value={query}
- onValueChange={setQuery}
- // keep the text clear of the dialog's close button, drawn over the
- // input's right end
- className="pr-8"
- />
- <CommandList
- className={isMobile ? "max-h-none flex-1" : "max-h-[60vh]"}
- >
- {isTooShort ? (
- <div className="py-6 text-center text-sm text-muted-foreground">
- {translate("crm.search.hint", { min: MIN_SEARCH_LENGTH })}
- </div>
- ) : error ? (
- <div
- role="alert"
- className="py-6 text-center text-sm text-destructive"
- >
- {translate("crm.search.error")}
- </div>
- ) : isPending ? (
- <div className="py-6 text-center text-sm text-muted-foreground">
- {translate("crm.common.loading")}
- </div>
- ) : (
- <>
- <CommandEmpty>{translate("crm.search.empty")}</CommandEmpty>
- {SEARCH_RESOURCES.map(({ name, icon: Icon, labelKey }) => {
- const groupResults = linkedResults.filter(
- ({ result }) => result.resource === name,
- );
- if (groupResults.length === 0) {
- return null;
- }
- return (
- <CommandGroup key={name} heading={translate(labelKey)}>
- {groupResults.map(({ result, url }) => {
- const title =
- result.title ||
- translate("crm.search.untitled_result");
- // A note's or task's title is the start of its text: when
- // the match is further in, show the text around it instead.
- const isTitleFromContent =
- !!result.content && result.content.startsWith(title);
- const snippet = result.content
- ? getSnippet(
- title,
- result.content,
- terms,
- isTitleFromContent
- ? TITLE_SNIPPET_RADIUS
- : undefined,
- )
- : null;
- const displayedTitle =
- isTitleFromContent && snippet ? snippet : title;
- const secondLine = isTitleFromContent ? null : snippet;
- return (
- <CommandItem
- key={`${result.resource}.${result.record_id}`}
- value={`${result.resource}.${result.record_id}`}
- onSelect={() => handleSelect(url)}
- className="items-start"
- >
- <Icon className="mt-0.5 shrink-0" />
- <div className="flex min-w-0 flex-1 flex-col gap-0.5">
- <div className="flex items-baseline gap-2">
- <span
- className={
- isTitleFromContent
- ? "line-clamp-2"
- : "truncate"
- }
- >
- <Highlighted
- text={displayedTitle}
- terms={terms}
- />
- </span>
- {result.subtitle ? (
- <span className="ml-auto shrink-0 text-xs text-muted-foreground">
- {result.subtitle}
- </span>
- ) : null}
- </div>
- {secondLine ? (
- <span className="line-clamp-2 text-xs text-muted-foreground">
- <Highlighted
- text={secondLine}
- terms={terms}
- />
- </span>
- ) : null}
- </div>
- </CommandItem>
- );
- })}
- </CommandGroup>
- );
- })}
- </>
- )}
- </CommandList>
- </Command>
- </DialogContent>
- </Dialog>
- );
-};
diff --git a/src/components/atomic-crm/search/getSearchResultUrl.ts b/src/components/atomic-crm/search/getSearchResultUrl.ts
deleted file mode 100644
index 0cbe23b8..00000000
--- a/src/components/atomic-crm/search/getSearchResultUrl.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import type { SearchResult } from "../types";
-
-type LinkableResult = Pick<
- SearchResult,
- "resource" | "record_id" | "contact_id" | "deal_id"
->;
-
-/**
- * Resolve the in-app URL for a global search result.
- *
- * Returns null when the result has no reachable page on the current layout:
- * the mobile app registers no deal resource, and a note or task whose parent
- * record is missing cannot be linked.
- */
-export const getSearchResultUrl = (
- result: LinkableResult,
- isMobile: boolean,
-): string | null => {
- switch (result.resource) {
- case "companies":
- return `/companies/${result.record_id}/show`;
- case "contacts":
- // On mobile, open the details tab: looking up a contact is usually
- // about reaching their email or phone, not their notes.
- return isMobile
- ? `/contacts/${result.record_id}/show?tab=details`
- : `/contacts/${result.record_id}/show`;
- case "deals":
- return isMobile ? null : `/deals/${result.record_id}/show`;
- case "tasks":
- // Tasks have no page of their own: link to the contact they belong to,
- // on mobile straight to its tasks tab.
- if (result.contact_id == null) {
- return null;
- }
- return isMobile
- ? `/contacts/${result.contact_id}/show?tab=tasks`
- : `/contacts/${result.contact_id}/show`;
- case "contact_notes":
- if (result.contact_id == null) {
- return null;
- }
- return isMobile
- ? `/contacts/${result.contact_id}/notes/${result.record_id}`
- : `/contacts/${result.contact_id}/show`;
- case "deal_notes":
- return isMobile || result.deal_id == null
- ? null
- : `/deals/${result.deal_id}/show`;
- default:
- return null;
- }
-};
diff --git a/src/components/atomic-crm/search/index.ts b/src/components/atomic-crm/search/index.ts
deleted file mode 100644
index 4c8e2d33..00000000
--- a/src/components/atomic-crm/search/index.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-export { GlobalSearchButton } from "./GlobalSearchButton";
-export { GlobalSearchDialog } from "./GlobalSearchDialog";
-export { getSearchResultUrl } from "./getSearchResultUrl";
-export { MIN_SEARCH_LENGTH } from "./useGlobalSearch";
diff --git a/src/components/atomic-crm/search/searchHighlight.test.ts b/src/components/atomic-crm/search/searchHighlight.test.ts
deleted file mode 100644
index f4bb8af1..00000000
--- a/src/components/atomic-crm/search/searchHighlight.test.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import {
- getSearchTerms,
- getSnippet,
- highlight,
- matchesAllTerms,
-} from "./searchHighlight";
-
-const matchedText = (text: string, query: string) =>
- highlight(text, getSearchTerms(query))
- .filter((part) => part.isMatch)
- .map((part) => part.text);
-
-describe("highlight", () => {
- it("marks the start of each word a query term begins", () => {
- expect(matchedText("Thomas Anderson", "tho and")).toEqual(["Tho", "And"]);
- });
-
- it("ignores accents and case on both sides", () => {
- expect(matchedText("Hélène Électricité", "HELENE elec")).toEqual([
- "Hélène",
- "Élec",
- ]);
- });
-
- it("folds letters that have no accent to strip, like the database does", () => {
- expect(matchedText("Łódź, Straße, Œuvre", "lodz strasse oeu")).toEqual([
- "Łódź",
- "Straße",
- "Œu",
- ]);
- });
-
- it("does not mark a term found in the middle of a word", () => {
- expect(matchedText("Thomas", "homas")).toEqual([]);
- });
-
- it("keeps the whole text, in order, across the parts", () => {
- const parts = highlight("Call Thomas, then Anna", getSearchTerms("th an"));
-
- expect(parts.map((part) => part.text).join("")).toBe(
- "Call Thomas, then Anna",
- );
- });
-});
-
-describe("matchesAllTerms", () => {
- it("requires every term to start a word, folding letters like the database", () => {
- expect(
- matchesAllTerms("Søren Kierkegaard", getSearchTerms("soren kier")),
- ).toBe(true);
- expect(
- matchesAllTerms("Søren Kierkegaard", getSearchTerms("soren ren")),
- ).toBe(false);
- });
-});
-
-describe("getSnippet", () => {
- const description =
- "A family bakery founded in 1952, known across the region for its sourdough bread and its weekly farmers market stall near the station, run by the third generation of the Martin family since the late nineties.";
-
- it("returns an excerpt around a term the title does not show", () => {
- const snippet = getSnippet(
- "Boulangerie Martin",
- description,
- getSearchTerms("sourdough"),
- );
-
- expect(snippet).toContain("sourdough bread");
- expect(snippet?.startsWith("…")).toBe(true);
- expect(snippet?.endsWith("…")).toBe(true);
- });
-
- it("returns null when the title already shows every term", () => {
- expect(
- getSnippet("Boulangerie Martin", description, getSearchTerms("boul mar")),
- ).toBeNull();
- });
-
- it("shows an excerpt when the title has the term past its visible start", () => {
- const note =
- "Met Thomas at the farmers market. He wants a weekly delivery of sourdough loaves for his café.";
-
- const snippet = getSnippet(note, note, getSearchTerms("sourdough"));
-
- expect(snippet).toContain("delivery of sourdough loaves");
- });
-
- it("does not end an excerpt on the separator between two fields", () => {
- // the 60-character window after "Web" ends inside the long last field,
- // so the cut falls back to the space right after the " · "
- const content = `Web-enabled · Voluptate in nihil dolor sit amet. · ${"x".repeat(80)}`;
-
- const snippet = getSnippet("Rachel", content, getSearchTerms("web"));
-
- expect(snippet).toBe("Web-enabled · Voluptate in nihil dolor sit amet.…");
- });
-
- it("looks only for the terms missing from the title", () => {
- const snippet = getSnippet(
- "Boulangerie Martin",
- description,
- getSearchTerms("martin farmers"),
- );
-
- expect(snippet).toContain("farmers market");
- });
-});
diff --git a/src/components/atomic-crm/search/getSearchResultUrl.test.ts b/src/components/atomic-crm/search/searchModel.test.ts
similarity index 56%
rename from src/components/atomic-crm/search/getSearchResultUrl.test.ts
rename to src/components/atomic-crm/search/searchModel.test.ts
index 3d73a30b..fea359ce 100644
--- a/src/components/atomic-crm/search/getSearchResultUrl.test.ts
+++ b/src/components/atomic-crm/search/searchModel.test.ts
@@ -1,6 +1,113 @@
import { describe, expect, it } from "vitest";
-import { getSearchResultUrl } from "./getSearchResultUrl";
+import {
+ getSearchResultUrl,
+ getSearchTerms,
+ getSnippet,
+ highlight,
+ matchesAllTerms,
+} from "./searchModel";
+
+const matchedText = (text: string, query: string) =>
+ highlight(text, getSearchTerms(query))
+ .filter((part) => part.isMatch)
+ .map((part) => part.text);
+
+describe("highlight", () => {
+ it("marks the start of each word a query term begins", () => {
+ expect(matchedText("Thomas Anderson", "tho and")).toEqual(["Tho", "And"]);
+ });
+
+ it("ignores accents and case on both sides", () => {
+ expect(matchedText("Hélène Électricité", "HELENE elec")).toEqual([
+ "Hélène",
+ "Élec",
+ ]);
+ });
+
+ it("folds letters that have no accent to strip, like the database does", () => {
+ expect(matchedText("Łódź, Straße, Œuvre", "lodz strasse oeu")).toEqual([
+ "Łódź",
+ "Straße",
+ "Œu",
+ ]);
+ });
+
+ it("does not mark a term found in the middle of a word", () => {
+ expect(matchedText("Thomas", "homas")).toEqual([]);
+ });
+
+ it("keeps the whole text, in order, across the parts", () => {
+ const parts = highlight("Call Thomas, then Anna", getSearchTerms("th an"));
+
+ expect(parts.map((part) => part.text).join("")).toBe(
+ "Call Thomas, then Anna",
+ );
+ });
+});
+
+describe("matchesAllTerms", () => {
+ it("requires every term to start a word, folding letters like the database", () => {
+ expect(
+ matchesAllTerms("Søren Kierkegaard", getSearchTerms("soren kier")),
+ ).toBe(true);
+ expect(
+ matchesAllTerms("Søren Kierkegaard", getSearchTerms("soren ren")),
+ ).toBe(false);
+ });
+});
+
+describe("getSnippet", () => {
+ const description =
+ "A family bakery founded in 1952, known across the region for its sourdough bread and its weekly farmers market stall near the station, run by the third generation of the Martin family since the late nineties.";
+
+ it("returns an excerpt around a term the title does not show", () => {
+ const snippet = getSnippet(
+ "Boulangerie Martin",
+ description,
+ getSearchTerms("sourdough"),
+ );
+
+ expect(snippet).toContain("sourdough bread");
+ expect(snippet?.startsWith("…")).toBe(true);
+ expect(snippet?.endsWith("…")).toBe(true);
+ });
+
+ it("returns null when the title already shows every term", () => {
+ expect(
+ getSnippet("Boulangerie Martin", description, getSearchTerms("boul mar")),
+ ).toBeNull();
+ });
+
+ it("shows an excerpt when the title has the term past its visible start", () => {
+ const note =
+ "Met Thomas at the farmers market. He wants a weekly delivery of sourdough loaves for his café.";
+
+ const snippet = getSnippet(note, note, getSearchTerms("sourdough"));
+
+ expect(snippet).toContain("delivery of sourdough loaves");
+ });
+
+ it("does not end an excerpt on the separator between two fields", () => {
+ // the 60-character window after "Web" ends inside the long last field,
+ // so the cut falls back to the space right after the " · "
+ const content = `Web-enabled · Voluptate in nihil dolor sit amet. · ${"x".repeat(80)}`;
+
+ const snippet = getSnippet("Rachel", content, getSearchTerms("web"));
+
+ expect(snippet).toBe("Web-enabled · Voluptate in nihil dolor sit amet.…");
+ });
+
+ it("looks only for the terms missing from the title", () => {
+ const snippet = getSnippet(
+ "Boulangerie Martin",
+ description,
+ getSearchTerms("martin farmers"),
+ );
+
+ expect(snippet).toContain("farmers market");
+ });
+});
describe("getSearchResultUrl", () => {
it("links a company to its show page", () => {
diff --git a/src/components/atomic-crm/search/searchHighlight.ts b/src/components/atomic-crm/search/searchModel.ts
similarity index 56%
rename from src/components/atomic-crm/search/searchHighlight.ts
rename to src/components/atomic-crm/search/searchModel.ts
index 2d0ecb41..e7b5ebbe 100644
--- a/src/components/atomic-crm/search/searchHighlight.ts
+++ b/src/components/atomic-crm/search/searchModel.ts
@@ -1,7 +1,13 @@
+import { Building2, DollarSign, FileText, ListTodo, User } from "lucide-react";
+import type { ComponentType } from "react";
+
+import type { SearchResourceName, SearchResult } from "../types";
+
/**
- * Client-side mirror of the matching done by `global_search` in Postgres:
- * text is unaccented and lowercased, split on anything that is not a letter or
- * a digit, and a query term matches a word it is a prefix of.
+ * Global search helpers, shared by the search dialog and the FakeRest
+ * emulation. Matching mirrors `global_search` in Postgres: text is unaccented
+ * and lowercased, split on anything that is not a letter or a digit, and a
+ * query term matches a word it is a prefix of.
*/
export type TextPart = { text: string; isMatch: boolean };
@@ -146,3 +152,91 @@ export const getSnippet = (
.replace(/^[\s·]+|[\s·]+$/g, "");
return `${start > 0 ? "…" : ""}${excerpt}${end < content.length ? "…" : ""}`;
};
+
+export type SearchResourceDescriptor = {
+ name: SearchResourceName;
+ icon: ComponentType<{ className?: string }>;
+ labelKey: string;
+};
+
+/** Result groups, in the order they appear in the search dialog. */
+export const SEARCH_RESOURCES: SearchResourceDescriptor[] = [
+ { name: "contacts", icon: User, labelKey: "crm.search.groups.contacts" },
+ {
+ name: "companies",
+ icon: Building2,
+ labelKey: "crm.search.groups.companies",
+ },
+ { name: "deals", icon: DollarSign, labelKey: "crm.search.groups.deals" },
+ { name: "tasks", icon: ListTodo, labelKey: "crm.search.groups.tasks" },
+ {
+ name: "contact_notes",
+ icon: FileText,
+ labelKey: "crm.search.groups.contact_notes",
+ },
+ {
+ name: "deal_notes",
+ icon: FileText,
+ labelKey: "crm.search.groups.deal_notes",
+ },
+];
+
+export const DESKTOP_SEARCH_RESOURCES: SearchResourceName[] =
+ SEARCH_RESOURCES.map(({ name }) => name);
+
+export const MOBILE_SEARCH_RESOURCES: SearchResourceName[] =
+ DESKTOP_SEARCH_RESOURCES.filter(
+ (name) => name !== "deals" && name !== "deal_notes",
+ );
+
+type LinkableResult = Pick<
+ SearchResult,
+ "resource" | "record_id" | "contact_id" | "deal_id"
+>;
+
+/**
+ * Resolve the in-app URL for a global search result.
+ *
+ * Returns null when the result has no reachable page on the current layout:
+ * the mobile app registers no deal resource, and a note or task whose parent
+ * record is missing cannot be linked.
+ */
+export const getSearchResultUrl = (
+ result: LinkableResult,
+ isMobile: boolean,
+): string | null => {
+ switch (result.resource) {
+ case "companies":
+ return `/companies/${result.record_id}/show`;
+ case "contacts":
+ // On mobile, open the details tab: looking up a contact is usually
+ // about reaching their email or phone, not their notes.
+ return isMobile
+ ? `/contacts/${result.record_id}/show?tab=details`
+ : `/contacts/${result.record_id}/show`;
+ case "deals":
+ return isMobile ? null : `/deals/${result.record_id}/show`;
+ case "tasks":
+ // Tasks have no page of their own: link to the contact they belong to,
+ // on mobile straight to its tasks tab.
+ if (result.contact_id == null) {
+ return null;
+ }
+ return isMobile
+ ? `/contacts/${result.contact_id}/show?tab=tasks`
+ : `/contacts/${result.contact_id}/show`;
+ case "contact_notes":
+ if (result.contact_id == null) {
+ return null;
+ }
+ return isMobile
+ ? `/contacts/${result.contact_id}/notes/${result.record_id}`
+ : `/contacts/${result.contact_id}/show`;
+ case "deal_notes":
+ return isMobile || result.deal_id == null
+ ? null
+ : `/deals/${result.deal_id}/show`;
+ default:
+ return null;
+ }
+};
diff --git a/src/components/atomic-crm/search/searchResources.ts b/src/components/atomic-crm/search/searchResources.ts
deleted file mode 100644
index da192452..00000000
--- a/src/components/atomic-crm/search/searchResources.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { Building2, DollarSign, FileText, ListTodo, User } from "lucide-react";
-import type { ComponentType } from "react";
-
-import type { SearchResourceName } from "../types";
-
-export type SearchResourceDescriptor = {
- name: SearchResourceName;
- icon: ComponentType<{ className?: string }>;
- labelKey: string;
-};
-
-/** Result groups, in the order they appear in the search dialog. */
-export const SEARCH_RESOURCES: SearchResourceDescriptor[] = [
- { name: "contacts", icon: User, labelKey: "crm.search.groups.contacts" },
- {
- name: "companies",
- icon: Building2,
- labelKey: "crm.search.groups.companies",
- },
- { name: "deals", icon: DollarSign, labelKey: "crm.search.groups.deals" },
- { name: "tasks", icon: ListTodo, labelKey: "crm.search.groups.tasks" },
- {
- name: "contact_notes",
- icon: FileText,
- labelKey: "crm.search.groups.contact_notes",
- },
- {
- name: "deal_notes",
- icon: FileText,
- labelKey: "crm.search.groups.deal_notes",
- },
-];
-
-export const DESKTOP_SEARCH_RESOURCES: SearchResourceName[] =
- SEARCH_RESOURCES.map(({ name }) => name);
-
-export const MOBILE_SEARCH_RESOURCES: SearchResourceName[] =
- DESKTOP_SEARCH_RESOURCES.filter(
- (name) => name !== "deals" && name !== "deal_notes",
- );
diff --git a/src/components/atomic-crm/search/useGlobalSearch.ts b/src/components/atomic-crm/search/useGlobalSearch.ts
deleted file mode 100644
index 36f5c7ed..00000000
--- a/src/components/atomic-crm/search/useGlobalSearch.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-import { useDataProvider } from "ra-core";
-import { useEffect, useState } from "react";
-
-import type { CrmDataProvider } from "../providers/types";
-import type { SearchResourceName } from "../types";
-
-export const MIN_SEARCH_LENGTH = 2;
-const DEBOUNCE_MS = 300;
-const MAX_RESULTS = 50;
-
-export const useDebouncedValue = <T>(value: T, delay: number): T => {
- const [debouncedValue, setDebouncedValue] = useState(value);
-
- useEffect(() => {
- const timeout = setTimeout(() => setDebouncedValue(value), delay);
- return () => clearTimeout(timeout);
- }, [value, delay]);
-
- return debouncedValue;
-};
-
-/**
- * Run the global search for a debounced search term.
- *
- * Stays idle until the term reaches MIN_SEARCH_LENGTH, so opening the dialog
- * does not fire a request. `resources` restricts the query server-side, so the
- * row cap is spent only on resources the current layout can actually link to.
- */
-export const useGlobalSearch = (
- query: string,
- resources: readonly SearchResourceName[],
-) => {
- const dataProvider = useDataProvider<CrmDataProvider>();
- const debouncedQuery = useDebouncedValue(query.trim(), DEBOUNCE_MS);
- const isEnabled = debouncedQuery.length >= MIN_SEARCH_LENGTH;
-
- const { data, isPending, error } = useQuery({
- queryKey: ["globalSearch", debouncedQuery, resources],
- queryFn: () =>
- dataProvider.globalSearch(debouncedQuery, resources, MAX_RESULTS),
- enabled: isEnabled,
- meta: { persist: false },
- // offlineFirst (the app default) pauses a failed search while offline,
- // leaving the dialog loading forever instead of reporting the error
- networkMode: "always",
- });
-
- return {
- results: isEnabled ? (data ?? []) : [],
- isPending: isEnabled && isPending,
- error,
- debouncedQuery,
- };
-};