Skip to content

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

Address UX feedback on the global search dialog

François Zaninotto8e0736fbb7c1
diff --git a/doc/src/content/docs/users/global-search.mdx b/doc/src/content/docs/users/global-search.mdx
index 5bca1b56..91c59963 100644
--- a/doc/src/content/docs/users/global-search.mdx
+++ b/doc/src/content/docs/users/global-search.mdx
@@ -36,6 +36,9 @@ Only the record's own fields count: searching `sourdough Anderson` does not
find a note about sourdough written on Thomas Anderson, since his name belongs
to the contact, not to the note.
+Matched words are highlighted. When the match is not in the result's name, an
+excerpt of the field it was found in shows under it.
+
## Good to know
- Search starts at **2 characters**.
diff --git a/src/components/atomic-crm/contacts/ContactShow.test.tsx b/src/components/atomic-crm/contacts/ContactShow.test.tsx
index 2f8e3cb8..d4ec7be3 100644
--- a/src/components/atomic-crm/contacts/ContactShow.test.tsx
+++ b/src/components/atomic-crm/contacts/ContactShow.test.tsx
@@ -7,6 +7,7 @@ import {
import { render } from "vitest-browser-react";
import { buildContact, StoryWrapper } from "@/test/StoryWrapper";
import { ContactAside } from "./ContactAside";
+import { ContactShow } from "./ContactShow";
import { MobileSuccess } from "./ContactShow.mobile.stories";
const mockIsMobile = vi.hoisted(() => vi.fn(() => true));
@@ -35,6 +36,21 @@ describe("ContactShow", () => {
.toBe(false);
});
+ it("opens on the tab named in the URL, as global search links to tasks", async () => {
+ const screen = await render(
+ <StoryWrapper
+ data={{ contacts: [buildContact({ id: 1 })] }}
+ initialEntries={["/?tab=tasks"]}
+ >
+ <ContactShow resource="contacts" id={1} />
+ </StoryWrapper>,
+ );
+
+ await expect
+ .element(screen.getByRole("tab", { name: "0 tasks" }))
+ .toHaveAttribute("aria-selected", "true");
+ });
+
it("updates the contact status from the aside", async () => {
mockIsMobile.mockReturnValue(false);
diff --git a/src/components/atomic-crm/contacts/ContactShow.tsx b/src/components/atomic-crm/contacts/ContactShow.tsx
index 6cc24ee1..d0e7ebd9 100644
--- a/src/components/atomic-crm/contacts/ContactShow.tsx
+++ b/src/components/atomic-crm/contacts/ContactShow.tsx
@@ -15,7 +15,7 @@ import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { Pencil } from "lucide-react";
-import { Link } from "react-router";
+import { Link, useSearchParams } from "react-router";
import MobileHeader from "../layout/MobileHeader";
import { MobileContent } from "../layout/MobileContent";
@@ -54,8 +54,15 @@ export const ContactShow = (props: ShowBaseProps = {}) => {
);
};
+const MOBILE_TABS = ["notes", "tasks", "details"];
+
const ContactShowContentMobile = () => {
const translate = useTranslate();
+ // `?tab=tasks` opens a tab directly, e.g. from a global search result
+ const [searchParams] = useSearchParams();
+ const requestedTab = searchParams.get("tab");
+ const initialTab =
+ requestedTab && MOBILE_TABS.includes(requestedTab) ? requestedTab : "notes";
const { defaultTitle, record, isPending } = useShowContext<Contact>();
const [noteCreateOpen, setNoteCreateOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
@@ -133,7 +140,7 @@ const ContactShowContentMobile = () => {
</div>
</div>
- <Tabs defaultValue="notes" className="w-full">
+ <Tabs key={initialTab} defaultValue={initialTab} className="w-full">
<TabsList className="grid w-full grid-cols-3 h-10">
<TabsTrigger value="notes">
{translate("resources.notes.name", { smart_count: 2 })}
diff --git a/src/components/atomic-crm/providers/commons/search.ts b/src/components/atomic-crm/providers/commons/search.ts
index 3b839efe..71d034ba 100644
--- a/src/components/atomic-crm/providers/commons/search.ts
+++ b/src/components/atomic-crm/providers/commons/search.ts
@@ -51,6 +51,13 @@ const getLabels = async <T extends { id: Identifier }>(
const contactName = (contact: Pick<Contact, "first_name" | "last_name">) =>
[contact.first_name, contact.last_name].filter(Boolean).join(" ");
+// Same fields, same separator as the `content` column of `global_search`.
+const joinFields = (...values: (string | null | undefined)[]) =>
+ values.filter(Boolean).join(" · ") || null;
+
+const attachmentTitles = (note: ContactNote | DealNote) =>
+ note.attachments?.map((attachment) => attachment.title).join(" ");
+
const byDateDesc = (a: SearchResult, b: SearchResult) =>
(b.date ?? "").localeCompare(a.date ?? "");
@@ -124,6 +131,15 @@ export async function getSearchResults(
contact_id: null,
deal_id: null,
date: company.created_at ?? null,
+ content: joinFields(
+ company.sector,
+ company.description,
+ company.website,
+ company.phone_number,
+ company.zipcode,
+ company.city,
+ company.state_abbr,
+ ),
})),
...contacts.map((contact) => ({
id: `contact.${contact.id}`,
@@ -134,6 +150,12 @@ export async function getSearchResults(
contact_id: contact.id,
deal_id: null,
date: contact.first_seen ?? null,
+ content: joinFields(
+ contact.title,
+ contact.background,
+ contact.email_jsonb?.map(({ email }) => email).join(" "),
+ contact.phone_jsonb?.map(({ number }) => number).join(" "),
+ ),
})),
...deals.map((deal) => ({
id: `deal.${deal.id}`,
@@ -147,6 +169,7 @@ export async function getSearchResults(
contact_id: null,
deal_id: deal.id,
date: deal.created_at ?? null,
+ content: joinFields(deal.category, deal.description),
})),
...tasks.map((task) => ({
id: `task.${task.id}`,
@@ -157,6 +180,7 @@ export async function getSearchResults(
contact_id: task.contact_id,
deal_id: null,
date: task.created_at ?? null,
+ content: joinFields(task.text, task.type),
})),
...contactNotes.map((note) => ({
id: `contactNote.${note.id}`,
@@ -167,6 +191,7 @@ export async function getSearchResults(
contact_id: note.contact_id,
deal_id: null,
date: note.date ?? null,
+ content: joinFields(note.text, attachmentTitles(note)),
})),
...dealNotes.map((note) => ({
id: `dealNote.${note.id}`,
@@ -177,6 +202,7 @@ export async function getSearchResults(
contact_id: null,
deal_id: note.deal_id,
date: note.date ?? null,
+ content: joinFields(note.text, attachmentTitles(note)),
})),
];
diff --git a/src/components/atomic-crm/search/GlobalSearchButton.tsx b/src/components/atomic-crm/search/GlobalSearchButton.tsx
index 1266b1a1..beafec97 100644
--- a/src/components/atomic-crm/search/GlobalSearchButton.tsx
+++ b/src/components/atomic-crm/search/GlobalSearchButton.tsx
@@ -18,10 +18,16 @@ const isEditableTarget = (target: EventTarget | null): boolean => {
);
};
+const SHORTCUT_LABEL =
+ typeof navigator !== "undefined" &&
+ /Mac|iPhone|iPad/.test(navigator.userAgent)
+ ? "⌘K"
+ : "Ctrl K";
+
/**
* Opens the global search dialog. `variant="icon"` renders the compact
- * icon-only trigger used on mobile; the default renders a labelled trigger for
- * the desktop app bar.
+ * icon-only trigger used on mobile; the default renders an input-like trigger
+ * for the desktop app bar.
*/
export const GlobalSearchButton = ({
variant = "labelled",
@@ -48,20 +54,34 @@ export const GlobalSearchButton = ({
return (
<>
- <Button
- variant="ghost"
- size={variant === "icon" ? "icon" : "sm"}
- onClick={() => setOpen(true)}
- aria-label={translate("crm.search.title")}
- aria-keyshortcuts="Control+K Meta+K"
- >
- <Search />
- {variant === "labelled" ? (
- <span className="hidden lg:inline text-muted-foreground">
+ {variant === "icon" ? (
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={() => setOpen(true)}
+ aria-label={translate("crm.search.title")}
+ >
+ <Search />
+ </Button>
+ ) : (
+ // Looks like a search field, so its purpose reads at a glance; the
+ // real input lives in the dialog it opens.
+ <Button
+ variant="outline"
+ onClick={() => setOpen(true)}
+ aria-label={translate("crm.search.title")}
+ aria-keyshortcuts="Control+K Meta+K"
+ className="mr-2 w-40 justify-start bg-background px-3 font-normal text-muted-foreground lg:w-64"
+ >
+ <Search />
+ <span className="flex-1 text-left">
{translate("crm.search.title")}
</span>
- ) : null}
- </Button>
+ <kbd className="pointer-events-none hidden rounded border bg-muted px-1.5 font-sans text-[10px] font-medium lg:inline">
+ {SHORTCUT_LABEL}
+ </kbd>
+ </Button>
+ )}
<GlobalSearchDialog open={open} onOpenChange={setOpen} />
</>
);
diff --git a/src/components/atomic-crm/search/GlobalSearchDialog.test.tsx b/src/components/atomic-crm/search/GlobalSearchDialog.test.tsx
index 27844df6..b0ce31c9 100644
--- a/src/components/atomic-crm/search/GlobalSearchDialog.test.tsx
+++ b/src/components/atomic-crm/search/GlobalSearchDialog.test.tsx
@@ -205,8 +205,9 @@ describe("GlobalSearchDialog", () => {
await screen.getByPlaceholder(PLACEHOLDER).fill("sourdough");
+ // the title is the note's text, cut to show the matched word
await expect
- .element(screen.getByText("Note on the zeroth contact about sourdough"))
+ .element(screen.getByText(/zeroth contact about sourdough/))
.toBeVisible();
await expect
.element(
@@ -250,6 +251,31 @@ describe("GlobalSearchDialog", () => {
.not.toBeInTheDocument();
});
+ it("shows and highlights where a record matched when its title does not", async () => {
+ const screen = await renderDialog();
+
+ // "supply" is only in the deal's description, not in its name
+ await screen.getByPlaceholder(PLACEHOLDER).fill("supply");
+
+ const match = screen
+ .getByRole("group", { name: "Deals" })
+ .getByText("supply", { exact: true });
+ await expect.element(match).toBeVisible();
+ expect(match.element().tagName).toBe("MARK");
+ });
+
+ it("highlights the query in result titles", async () => {
+ const screen = await renderDialog();
+
+ await screen.getByPlaceholder(PLACEHOLDER).fill("boul");
+
+ const match = screen
+ .getByRole("group", { name: "Companies" })
+ .getByText("Boul", { exact: true });
+ await expect.element(match).toBeVisible();
+ expect(match.element().tagName).toBe("MARK");
+ });
+
it("reports when nothing matches", async () => {
const screen = await renderDialog();
diff --git a/src/components/atomic-crm/search/GlobalSearchDialog.tsx b/src/components/atomic-crm/search/GlobalSearchDialog.tsx
index 6ca5b4cd..339f58fb 100644
--- a/src/components/atomic-crm/search/GlobalSearchDialog.tsx
+++ b/src/components/atomic-crm/search/GlobalSearchDialog.tsx
@@ -14,6 +14,7 @@ import { useIsMobile } from "@/hooks/use-mobile";
import type { SearchResult } from "../types";
import { getSearchResultUrl } from "./getSearchResultUrl";
+import { getSearchTerms, getSnippet, highlight } from "./searchHighlight";
import {
DESKTOP_SEARCH_RESOURCES,
MOBILE_SEARCH_RESOURCES,
@@ -23,6 +24,29 @@ import { MIN_SEARCH_LENGTH, useGlobalSearch } from "./useGlobalSearch";
type LinkedResult = { result: SearchResult; url: string };
+// Desktop: pinned near the top so the box grows downwards as results arrive
+// instead of re-centering on every keystroke. Mobile: the whole screen.
+const DESKTOP_DIALOG_CLASSES = "top-[12vh] translate-y-0 sm:max-w-xl";
+const MOBILE_DIALOG_CLASSES =
+ "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";
+
+// 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,
@@ -63,6 +87,7 @@ export const GlobalSearchDialog = ({
};
const isTooShort = debouncedQuery.length < MIN_SEARCH_LENGTH;
+ const terms = useMemo(() => getSearchTerms(debouncedQuery), [debouncedQuery]);
return (
<CommandDialog
@@ -71,13 +96,14 @@ export const GlobalSearchDialog = ({
title={translate("crm.search.title")}
description={translate("crm.search.placeholder")}
shouldFilter={false}
+ className={isMobile ? MOBILE_DIALOG_CLASSES : DESKTOP_DIALOG_CLASSES}
>
<CommandInput
placeholder={translate("crm.search.placeholder")}
value={query}
onValueChange={setQuery}
/>
- <CommandList className="max-h-[60vh]">
+ <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 })}
@@ -105,24 +131,59 @@ export const GlobalSearchDialog = ({
}
return (
<CommandGroup key={name} heading={translate(labelKey)}>
- {groupResults.map(({ result, url }) => (
- <CommandItem
- key={result.id}
- value={String(result.id)}
- onSelect={() => handleSelect(url)}
- >
- <Icon className="shrink-0" />
- <span className="truncate">
- {result.title ||
- translate("crm.search.untitled_result")}
- </span>
- {result.subtitle ? (
- <span className="ml-auto shrink-0 pl-2 text-xs text-muted-foreground">
- {result.subtitle}
- </span>
- ) : null}
- </CommandItem>
- ))}
+ {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.id}
+ value={String(result.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>
);
})}
diff --git a/src/components/atomic-crm/search/getSearchResultUrl.test.ts b/src/components/atomic-crm/search/getSearchResultUrl.test.ts
index aefb8245..426f0d27 100644
--- a/src/components/atomic-crm/search/getSearchResultUrl.test.ts
+++ b/src/components/atomic-crm/search/getSearchResultUrl.test.ts
@@ -61,6 +61,17 @@ describe("getSearchResultUrl", () => {
expect(getSearchResultUrl(result, false)).toBe("/contacts/4/show");
});
+ it("opens a task's contact on its tasks tab on mobile", () => {
+ const result = buildResult({
+ resource: "tasks",
+ record_id: 11,
+ contact_id: 4,
+ deal_id: null,
+ });
+
+ expect(getSearchResultUrl(result, true)).toBe("/contacts/4/show?tab=tasks");
+ });
+
it("links a contact note to the contact page on desktop", () => {
const result = buildResult({
resource: "contact_notes",
diff --git a/src/components/atomic-crm/search/getSearchResultUrl.ts b/src/components/atomic-crm/search/getSearchResultUrl.ts
index 30076d81..061f7253 100644
--- a/src/components/atomic-crm/search/getSearchResultUrl.ts
+++ b/src/components/atomic-crm/search/getSearchResultUrl.ts
@@ -24,10 +24,14 @@ export const getSearchResultUrl = (
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.
- return result.contact_id != null
- ? `/contacts/${result.contact_id}/show`
- : null;
+ // 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;
diff --git a/src/components/atomic-crm/search/searchHighlight.test.ts b/src/components/atomic-crm/search/searchHighlight.test.ts
new file mode 100644
index 00000000..b27c2434
--- /dev/null
+++ b/src/components/atomic-crm/search/searchHighlight.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from "vitest";
+
+import { getSearchTerms, getSnippet, highlight } 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("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("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("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/searchHighlight.ts b/src/components/atomic-crm/search/searchHighlight.ts
new file mode 100644
index 00000000..efc55e8c
--- /dev/null
+++ b/src/components/atomic-crm/search/searchHighlight.ts
@@ -0,0 +1,107 @@
+/**
+ * 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.
+ */
+
+export type TextPart = { text: string; isMatch: boolean };
+
+type Range = { start: number; end: number; term: string };
+
+const WORD = /[\p{L}\p{N}]+/gu;
+const SNIPPET_RADIUS = 60;
+// Long titles (a note's first 200 characters) are truncated on screen, so a
+// term past this point does not count as shown by the title.
+const VISIBLE_TITLE_LENGTH = 30;
+
+const normalize = (value: string): string =>
+ value.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase();
+
+export const getSearchTerms = (query: string): string[] => [
+ ...new Set(normalize(query).match(WORD) ?? []),
+];
+
+/** Length of `word` covered by `term` when it is a prefix of it, else 0. */
+const prefixLength = (word: string, term: string): number => {
+ let normalized = "";
+ let length = 0;
+ for (const char of word) {
+ normalized += normalize(char);
+ length += char.length;
+ if (normalized.length >= term.length) {
+ return normalized.startsWith(term) ? length : 0;
+ }
+ if (!term.startsWith(normalized)) {
+ return 0;
+ }
+ }
+ return 0;
+};
+
+const findMatches = (text: string, terms: string[]): Range[] =>
+ [...text.matchAll(WORD)].flatMap((word) => {
+ const start = word.index ?? 0;
+ const best = terms
+ .map((term) => ({ term, length: prefixLength(word[0], term) }))
+ .reduce((a, b) => (b.length > a.length ? b : a), {
+ term: "",
+ length: 0,
+ });
+ return best.length > 0
+ ? [{ start, end: start + best.length, term: best.term }]
+ : [];
+ });
+
+/** Split `text` into parts, flagging the ones matched by a search term. */
+export const highlight = (text: string, terms: string[]): TextPart[] => {
+ const parts: TextPart[] = [];
+ let cursor = 0;
+ for (const { start, end } of findMatches(text, terms)) {
+ if (start > cursor) {
+ parts.push({ text: text.slice(cursor, start), isMatch: false });
+ }
+ parts.push({ text: text.slice(start, end), isMatch: true });
+ cursor = end;
+ }
+ if (cursor < text.length) {
+ parts.push({ text: text.slice(cursor), isMatch: false });
+ }
+ return parts;
+};
+
+/**
+ * An excerpt of `content` around the first term that the visible start of
+ * `title` does not already show, or null when it shows every term (or content
+ * has none of them).
+ */
+export const getSnippet = (
+ title: string,
+ content: string,
+ terms: string[],
+ radius = SNIPPET_RADIUS,
+): string | null => {
+ const shown = new Set(
+ findMatches(title.slice(0, VISIBLE_TITLE_LENGTH), terms).map(
+ ({ term }) => term,
+ ),
+ );
+ const missing = terms.filter((term) => !shown.has(term));
+ if (missing.length === 0) {
+ return null;
+ }
+ const match = findMatches(content, missing)[0];
+ if (!match) {
+ return null;
+ }
+ const from = Math.max(0, match.start - radius);
+ const to = Math.min(content.length, match.end + radius);
+ // cut on spaces so the excerpt never starts or ends mid-word
+ const start =
+ from === 0
+ ? 0
+ : Math.min(content.indexOf(" ", from) + 1 || from, match.start);
+ const lastSpace = content.lastIndexOf(" ", to);
+ const end = to === content.length || lastSpace <= match.end ? to : lastSpace;
+ const excerpt = content.slice(start, end).replace(/\s+/g, " ").trim();
+ return `${start > 0 ? "…" : ""}${excerpt}${end < content.length ? "…" : ""}`;
+};
diff --git a/src/components/atomic-crm/types.ts b/src/components/atomic-crm/types.ts
index 2ed27154..d79dea5f 100644
--- a/src/components/atomic-crm/types.ts
+++ b/src/components/atomic-crm/types.ts
@@ -245,4 +245,6 @@ export type SearchResult = {
contact_id: Identifier | null;
deal_id: Identifier | null;
date: string | null;
+ /** The searched fields, to show and highlight where the query matched. */
+ content: string | null;
};
diff --git a/src/components/ui/command.tsx b/src/components/ui/command.tsx
index 4310486e..4131280d 100644
--- a/src/components/ui/command.tsx
+++ b/src/components/ui/command.tsx
@@ -31,16 +31,18 @@ function CommandDialog({
title = "Command Palette",
description = "Search for a command to run...",
shouldFilter,
+ className,
children,
...props
}: React.ComponentProps<typeof Dialog> & {
title?: string
description?: string
shouldFilter?: boolean
+ className?: string
}) {
return (
<Dialog {...props}>
- <DialogContent className="overflow-hidden p-0">
+ <DialogContent className={cn("overflow-hidden p-0", className)}>
<DialogHeader className="sr-only">
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
diff --git a/supabase/migrations/20261010054346_global_search.sql b/supabase/migrations/20261010054346_global_search.sql
index a9dbb62b..168fab75 100644
--- a/supabase/migrations/20261010054346_global_search.sql
+++ b/supabase/migrations/20261010054346_global_search.sql
@@ -111,7 +111,8 @@ alter table public.deal_notes alter column fts set statistics 10000;
-- Each branch takes its own newest max_results matches, so the union never
-- holds more than 6 * max_results rows, and the lookups that build display
--- labels only run on those. The SQL is built per call with the tsquery inlined
+-- labels only run on those. `content` carries the searched fields in their
+-- original form, so the client can show and highlight where the words matched. The SQL is built per call with the tsquery inlined
-- as a literal: with a parameter the planner could not tell a rare word (use
-- the GIN index) from a common one (walk the date index).
create or replace function public.global_search(
@@ -126,7 +127,8 @@ create or replace function public.global_search(
subtitle text,
contact_id bigint,
deal_id bigint,
- date timestamp with time zone
+ date timestamp with time zone,
+ content text
)
language plpgsql stable security invoker
set search_path to ''
@@ -135,21 +137,26 @@ declare
tsq tsquery := public.search_query(query);
branch_templates constant jsonb := jsonb_build_object(
'companies', $q$
- select 'company.' || c.id, 'companies', c.id, c.name, c.sector, null::bigint, null::bigint, c.created_at
+ select 'company.' || c.id, 'companies', c.id, c.name, c.sector, null::bigint, null::bigint, c.created_at,
+ concat_ws(' · ', c.sector, c.description, c.website::text, c.phone_number, c.zipcode, c.city, c.state_abbr)
from public.companies c
where c.fts @@ %1$L::tsquery
order by c.created_at desc
limit %2$s $q$,
'contacts', $q$
select 'contact.' || co.id, 'contacts', co.id, concat_ws(' ', co.first_name, co.last_name),
- (select cc.name from public.companies cc where cc.id = co.company_id), co.id, null::bigint, co.first_seen
+ (select cc.name from public.companies cc where cc.id = co.company_id), co.id, null::bigint, co.first_seen,
+ concat_ws(' · ', co.title, co.background,
+ (select string_agg(e ->> 'email', ' ') from jsonb_array_elements(co.email_jsonb) e),
+ (select string_agg(p ->> 'number', ' ') from jsonb_array_elements(co.phone_jsonb) p))
from public.contacts co
where co.fts @@ %1$L::tsquery
order by co.first_seen desc nulls last
limit %2$s $q$,
'deals', $q$
select 'deal.' || d.id, 'deals', d.id, d.name,
- (select dc.name from public.companies dc where dc.id = d.company_id), null::bigint, d.id, d.created_at
+ (select dc.name from public.companies dc where dc.id = d.company_id), null::bigint, d.id, d.created_at,
+ concat_ws(' · ', d.category, d.description)
from public.deals d
where d.archived_at is null and d.fts @@ %1$L::tsquery
order by d.created_at desc
@@ -157,7 +164,8 @@ declare
'tasks', $q$
select 'task.' || t.id, 'tasks', t.id, left(t.text, 200),
(select concat_ws(' ', tc.first_name, tc.last_name) from public.contacts tc where tc.id = t.contact_id),
- t.contact_id, null::bigint, t.created_at
+ t.contact_id, null::bigint, t.created_at,
+ concat_ws(' · ', t.text, t.type)
from public.tasks t
where t.done_date is null and t.fts @@ %1$L::tsquery
order by t.created_at desc
@@ -165,13 +173,15 @@ declare
'contact_notes', $q$
select 'contactNote.' || cn.id, 'contact_notes', cn.id, left(cn.text, 200),
(select concat_ws(' ', nc.first_name, nc.last_name) from public.contacts nc where nc.id = cn.contact_id),
- cn.contact_id, null::bigint, cn.date
+ cn.contact_id, null::bigint, cn.date,
+ concat_ws(' · ', cn.text, public.search_attachment_titles(cn.attachments))
from public.contact_notes cn
where cn.fts @@ %1$L::tsquery
order by cn.date desc nulls last
limit %2$s $q$,
'deal_notes', $q$
- select 'dealNote.' || dn.id, 'deal_notes', dn.id, left(dn.text, 200), nd.name, null::bigint, dn.deal_id, dn.date
+ select 'dealNote.' || dn.id, 'deal_notes', dn.id, left(dn.text, 200), nd.name, null::bigint, dn.deal_id, dn.date,
+ concat_ws(' · ', dn.text, public.search_attachment_titles(dn.attachments))
from public.deal_notes dn
join public.deals nd on nd.id = dn.deal_id
where nd.archived_at is null and dn.fts @@ %1$L::tsquery
diff --git a/supabase/schemas/08_search.sql b/supabase/schemas/08_search.sql
index 56228c64..9903e3c6 100644
--- a/supabase/schemas/08_search.sql
+++ b/supabase/schemas/08_search.sql
@@ -98,7 +98,8 @@ alter table public.deal_notes alter column fts set statistics 10000;
-- Each branch takes its own newest max_results matches, so the union never
-- holds more than 6 * max_results rows, and the lookups that build display
--- labels only run on those. The SQL is built per call with the tsquery inlined
+-- labels only run on those. `content` carries the searched fields in their
+-- original form, so the client can show and highlight where the words matched. The SQL is built per call with the tsquery inlined
-- as a literal: with a parameter the planner could not tell a rare word (use
-- the GIN index) from a common one (walk the date index).
create or replace function public.global_search(
@@ -113,7 +114,8 @@ create or replace function public.global_search(
subtitle text,
contact_id bigint,
deal_id bigint,
- date timestamp with time zone
+ date timestamp with time zone,
+ content text
)
language plpgsql stable security invoker
set search_path to ''
@@ -122,21 +124,26 @@ declare
tsq tsquery := public.search_query(query);
branch_templates constant jsonb := jsonb_build_object(
'companies', $q$
- select 'company.' || c.id, 'companies', c.id, c.name, c.sector, null::bigint, null::bigint, c.created_at
+ select 'company.' || c.id, 'companies', c.id, c.name, c.sector, null::bigint, null::bigint, c.created_at,
+ concat_ws(' · ', c.sector, c.description, c.website::text, c.phone_number, c.zipcode, c.city, c.state_abbr)
from public.companies c
where c.fts @@ %1$L::tsquery
order by c.created_at desc
limit %2$s $q$,
'contacts', $q$
select 'contact.' || co.id, 'contacts', co.id, concat_ws(' ', co.first_name, co.last_name),
- (select cc.name from public.companies cc where cc.id = co.company_id), co.id, null::bigint, co.first_seen
+ (select cc.name from public.companies cc where cc.id = co.company_id), co.id, null::bigint, co.first_seen,
+ concat_ws(' · ', co.title, co.background,
+ (select string_agg(e ->> 'email', ' ') from jsonb_array_elements(co.email_jsonb) e),
+ (select string_agg(p ->> 'number', ' ') from jsonb_array_elements(co.phone_jsonb) p))
from public.contacts co
where co.fts @@ %1$L::tsquery
order by co.first_seen desc nulls last
limit %2$s $q$,
'deals', $q$
select 'deal.' || d.id, 'deals', d.id, d.name,
- (select dc.name from public.companies dc where dc.id = d.company_id), null::bigint, d.id, d.created_at
+ (select dc.name from public.companies dc where dc.id = d.company_id), null::bigint, d.id, d.created_at,
+ concat_ws(' · ', d.category, d.description)
from public.deals d
where d.archived_at is null and d.fts @@ %1$L::tsquery
order by d.created_at desc
@@ -144,7 +151,8 @@ declare
'tasks', $q$
select 'task.' || t.id, 'tasks', t.id, left(t.text, 200),
(select concat_ws(' ', tc.first_name, tc.last_name) from public.contacts tc where tc.id = t.contact_id),
- t.contact_id, null::bigint, t.created_at
+ t.contact_id, null::bigint, t.created_at,
+ concat_ws(' · ', t.text, t.type)
from public.tasks t
where t.done_date is null and t.fts @@ %1$L::tsquery
order by t.created_at desc
@@ -152,13 +160,15 @@ declare
'contact_notes', $q$
select 'contactNote.' || cn.id, 'contact_notes', cn.id, left(cn.text, 200),
(select concat_ws(' ', nc.first_name, nc.last_name) from public.contacts nc where nc.id = cn.contact_id),
- cn.contact_id, null::bigint, cn.date
+ cn.contact_id, null::bigint, cn.date,
+ concat_ws(' · ', cn.text, public.search_attachment_titles(cn.attachments))
from public.contact_notes cn
where cn.fts @@ %1$L::tsquery
order by cn.date desc nulls last
limit %2$s $q$,
'deal_notes', $q$
- select 'dealNote.' || dn.id, 'deal_notes', dn.id, left(dn.text, 200), nd.name, null::bigint, dn.deal_id, dn.date
+ select 'dealNote.' || dn.id, 'deal_notes', dn.id, left(dn.text, 200), nd.name, null::bigint, dn.deal_id, dn.date,
+ concat_ws(' · ', dn.text, public.search_attachment_titles(dn.attachments))
from public.deal_notes dn
join public.deals nd on nd.id = dn.deal_id
where nd.archived_at is null and dn.fts @@ %1$L::tsquery