Skip to content

armgit / crm

Public Imported from GitHub
0

Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.

TypeScript

feat(app): search company dropdowns instead of scrolling them (#125)

Guzman Pintos3b558a82155d
diff --git a/apps/app/app/(app)/[slug]/contacts/contacts-bulk-actions.tsx b/apps/app/app/(app)/[slug]/contacts/contacts-bulk-actions.tsx
index c992755b..50139c4d 100644
--- a/apps/app/app/(app)/[slug]/contacts/contacts-bulk-actions.tsx
+++ b/apps/app/app/(app)/[slug]/contacts/contacts-bulk-actions.tsx
@@ -5,7 +5,6 @@ import TrashCan from "@carbon/icons-react/es/TrashCan";
import {
DropdownMenuGroup,
DropdownMenuItem,
- DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
@@ -13,7 +12,7 @@ import {
} from "@crm/ui/components/dropdown-menu";
import { formatCount } from "@crm/ui/lib/format";
import { useMutation, useQuery } from "@tanstack/react-query";
-import { useState } from "react";
+import { useRef, useState } from "react";
import { toast } from "sonner";
import {
BulkActionsMenu,
@@ -21,6 +20,7 @@ import {
BulkOwnerMenu,
reportBulk,
} from "@/components/crm/bulk-actions";
+import { CompanyMenuSearch } from "@/components/crm/company-picker";
import { useCrmCache } from "@/lib/trpc/cache";
import { useTRPC } from "@/lib/trpc/client";
@@ -38,8 +38,9 @@ export function ContactsBulkActions({
const trpc = useTRPC();
const cache = useCrmCache();
const users = useQuery(trpc.users.list.queryOptions());
- const companies = useQuery(trpc.companies.options.queryOptions({ q: "" }));
const [confirming, setConfirming] = useState(false);
+ const [menuOpen, setMenuOpen] = useState(false);
+ const companySearch = useRef<HTMLInputElement>(null);
const onError = (error: { message: string }) => toast.error(error.message);
@@ -99,7 +100,11 @@ export function ContactsBulkActions({
return (
<>
- <BulkActionsMenu pending={pending}>
+ <BulkActionsMenu
+ pending={pending}
+ open={menuOpen}
+ onOpenChange={setMenuOpen}
+ >
<BulkOwnerMenu
users={users.data ?? []}
unassignedLabel="Nobody"
@@ -107,28 +112,22 @@ export function ContactsBulkActions({
/>
<DropdownMenuSub>
<DropdownMenuSubTrigger>Move to company</DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="max-h-72 overflow-y-auto">
- <DropdownMenuGroup>
- <DropdownMenuItem
- onSelect={() => setCompany.mutate({ ids, companyId: null })}
- >
- No company
- </DropdownMenuItem>
- {companies.data?.length === 0 ? (
- <DropdownMenuLabel>No companies yet.</DropdownMenuLabel>
- ) : (
- companies.data?.map((company) => (
- <DropdownMenuItem
- key={company.id}
- onSelect={() =>
- setCompany.mutate({ ids, companyId: company.id })
- }
- >
- {company.name}
- </DropdownMenuItem>
- ))
- )}
- </DropdownMenuGroup>
+ <DropdownMenuSubContent
+ className="w-64 p-0"
+ onFocus={(event) => {
+ if (event.target === event.currentTarget) {
+ companySearch.current?.focus();
+ }
+ }}
+ >
+ <CompanyMenuSearch
+ none="No company"
+ inputRef={companySearch}
+ onSelect={(companyId) => {
+ setMenuOpen(false);
+ setCompany.mutate({ ids, companyId });
+ }}
+ />
</DropdownMenuSubContent>
</DropdownMenuSub>
<DropdownMenuGroup>
diff --git a/apps/app/app/(app)/[slug]/contacts/contacts-table.tsx b/apps/app/app/(app)/[slug]/contacts/contacts-table.tsx
index 313a273d..8b7ccb90 100644
--- a/apps/app/app/(app)/[slug]/contacts/contacts-table.tsx
+++ b/apps/app/app/(app)/[slug]/contacts/contacts-table.tsx
@@ -7,9 +7,10 @@ import {
} from "@crm/ui/components/data-table";
import { EmptyCellValue } from "@crm/ui/components/empty-cell";
import { PersonAvatar } from "@crm/ui/components/person-avatar";
+import { useSearchInput } from "@crm/ui/hooks/use-search-input";
import { useTableSelection } from "@crm/ui/hooks/use-table-selection";
import { useQuery } from "@tanstack/react-query";
-import { useMemo } from "react";
+import { useMemo, useState } from "react";
import { CompanyCell } from "@/components/crm/company-cell";
import { contactName } from "@/components/crm/contact-name";
import { useFieldColumns } from "@/components/crm/fields/field-columns";
@@ -130,7 +131,16 @@ export function ContactsTable() {
placeholderData: (previous) => previous,
});
const users = useQuery(trpc.users.list.queryOptions());
- const companies = useQuery(trpc.companies.options.queryOptions({ q: "" }));
+
+ const [companyQuery, setCompanyQuery] = useState("");
+ const [companyText, setCompanyText] = useSearchInput(
+ companyQuery,
+ setCompanyQuery,
+ );
+ const companies = useQuery({
+ ...trpc.companies.options.queryOptions({ q: companyQuery }),
+ placeholderData: (previous) => previous,
+ });
const rows = contacts.data?.rows ?? [];
const selection = useTableSelection(
@@ -154,8 +164,15 @@ export function ContactsTable() {
{
id: "company",
label: "Company",
+ searchable: true,
+ search: companyText,
+ onSearchChange: setCompanyText,
+ stale: companies.isFetching || companyText.trim() !== companyQuery.trim(),
+ empty: companies.isFetching ? "Searching…" : "No company matches.",
options: [
- { value: "none", label: "No company" },
+ ...(companyQuery.trim()
+ ? []
+ : [{ value: "none", label: "No company" }]),
...(companies.data ?? []).map((company) => ({
value: company.id,
label: company.name,
diff --git a/apps/app/app/(app)/[slug]/contacts/create-contact-sheet.tsx b/apps/app/app/(app)/[slug]/contacts/create-contact-sheet.tsx
index 795e3532..1494143e 100644
--- a/apps/app/app/(app)/[slug]/contacts/create-contact-sheet.tsx
+++ b/apps/app/app/(app)/[slug]/contacts/create-contact-sheet.tsx
@@ -27,6 +27,7 @@ import { useMutation, useQuery } from "@tanstack/react-query";
import { parseAsBoolean, useQueryState } from "nuqs";
import { type ComponentProps, Suspense, useId, useState } from "react";
import { toast } from "sonner";
+import { CompanyPicker } from "@/components/crm/company-picker";
import { useOpenRecord } from "@/components/crm/record-sheet/record-stack";
import { useCrmCache } from "@/lib/trpc/cache";
import { useTRPC } from "@/lib/trpc/client";
@@ -72,7 +73,6 @@ function CreateContactForm({ companyId }: { companyId?: string }) {
const titleId = useId();
const users = useQuery(trpc.users.list.queryOptions());
- const companies = useQuery(trpc.companies.options.queryOptions({ q: "" }));
const create = useMutation(
trpc.contacts.create.mutationOptions({
@@ -167,19 +167,12 @@ function CreateContactForm({ companyId }: { companyId?: string }) {
<Field>
<FieldLabel htmlFor="create-contact-company">Company</FieldLabel>
- <Select value={company} onValueChange={setCompany}>
- <SelectTrigger id="create-contact-company">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value={NONE}>No company</SelectItem>
- {(companies.data ?? []).map((option) => (
- <SelectItem key={option.id} value={option.id}>
- {option.name}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
+ <CompanyPicker
+ id="create-contact-company"
+ value={company}
+ onValueChange={setCompany}
+ none={{ value: NONE, label: "No company" }}
+ />
</Field>
<Field>
diff --git a/apps/app/app/(app)/[slug]/deals/create-deal-sheet.tsx b/apps/app/app/(app)/[slug]/deals/create-deal-sheet.tsx
index a0d5a91d..6d3e57b8 100644
--- a/apps/app/app/(app)/[slug]/deals/create-deal-sheet.tsx
+++ b/apps/app/app/(app)/[slug]/deals/create-deal-sheet.tsx
@@ -34,6 +34,7 @@ import { useMutation, useQuery } from "@tanstack/react-query";
import { parseAsBoolean, useQueryState } from "nuqs";
import { type ComponentProps, Suspense, useId, useState } from "react";
import { toast } from "sonner";
+import { CompanyPicker } from "@/components/crm/company-picker";
import { useOpenRecord } from "@/components/crm/record-sheet/record-stack";
import { dealStageLabel, OPEN_STAGES } from "@/lib/deal-stage";
import { useCrmCache } from "@/lib/trpc/cache";
@@ -80,7 +81,6 @@ function CreateDealForm({ companyId }: { companyId?: string }) {
const closeDateId = useId();
const users = useQuery(trpc.users.list.queryOptions());
- const companies = useQuery(trpc.companies.options.queryOptions({ q: "" }));
const me = useQuery(trpc.users.me.queryOptions());
const currencies = useQuery(trpc.currency.settings.queryOptions());
@@ -154,18 +154,11 @@ function CreateDealForm({ companyId }: { companyId?: string }) {
<Field>
<FieldLabel htmlFor="create-deal-company">Company</FieldLabel>
- <Select value={company} onValueChange={setCompany}>
- <SelectTrigger id="create-deal-company">
- <SelectValue placeholder="Choose a company" />
- </SelectTrigger>
- <SelectContent>
- {(companies.data ?? []).map((option) => (
- <SelectItem key={option.id} value={option.id}>
- {option.name}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
+ <CompanyPicker
+ id="create-deal-company"
+ value={company}
+ onValueChange={setCompany}
+ />
</Field>
<Field>
diff --git a/apps/app/components/crm/bulk-actions.tsx b/apps/app/components/crm/bulk-actions.tsx
index 8aaa954b..7c15c899 100644
--- a/apps/app/components/crm/bulk-actions.tsx
+++ b/apps/app/components/crm/bulk-actions.tsx
@@ -57,13 +57,17 @@ export function reportBulk(
export function BulkActionsMenu({
pending,
+ open,
+ onOpenChange,
children,
}: {
pending?: boolean;
+ open?: boolean;
+ onOpenChange?: (open: boolean) => void;
children: ReactNode;
}) {
return (
- <DropdownMenu>
+ <DropdownMenu open={open} onOpenChange={onOpenChange}>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm" disabled={pending}>
{pending ? <Spinner /> : null}
diff --git a/apps/app/components/crm/company-picker.tsx b/apps/app/components/crm/company-picker.tsx
new file mode 100644
index 00000000..31c870bb
--- /dev/null
+++ b/apps/app/components/crm/company-picker.tsx
@@ -0,0 +1,199 @@
+"use client";
+
+import { Combobox, type ComboboxOption } from "@crm/ui/components/combobox";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from "@crm/ui/components/command";
+import { Spinner } from "@crm/ui/components/spinner";
+import { useSearchInput } from "@crm/ui/hooks/use-search-input";
+import { cn } from "@crm/ui/lib/utils";
+import { useQuery } from "@tanstack/react-query";
+import { type Ref, useId, useState } from "react";
+import { PROPERTY_LABEL, PROPERTY_ROW } from "@/components/detail-sheet";
+import { useTRPC } from "@/lib/trpc/client";
+
+export function CompanyPicker({
+ id,
+ value,
+ onValueChange,
+ placeholder = "Choose a company",
+ none,
+ selected,
+ disabled,
+ variant,
+ className,
+}: {
+ id?: string;
+ value: string;
+ onValueChange: (value: string) => void;
+ placeholder?: string;
+ none?: { value: string; label: string };
+ selected?: ComboboxOption;
+ disabled?: boolean;
+ variant?: "default" | "ghost";
+ className?: string;
+}) {
+ const trpc = useTRPC();
+
+ const [query, setQuery] = useState("");
+ const [text, setText] = useSearchInput(query, setQuery);
+ const [chosen, setChosen] = useState<ComboboxOption | null>(null);
+
+ const companies = useQuery({
+ ...trpc.companies.options.queryOptions({ q: query }),
+ placeholderData: (previous) => previous,
+ });
+
+ const matches: ComboboxOption[] = (companies.data ?? []).map((company) => ({
+ value: company.id,
+ label: company.name,
+ hint: company.domain ?? undefined,
+ keywords: company.domain ? [company.domain] : undefined,
+ }));
+
+ const cleared = none ? [{ value: none.value, label: none.label }] : [];
+ const options = query.trim() ? matches : [...cleared, ...matches];
+ const stale = companies.isFetching || text.trim() !== query.trim();
+
+ const current =
+ chosen?.value === value
+ ? chosen
+ : ([...cleared, ...matches].find((option) => option.value === value) ??
+ (selected?.value === value ? selected : undefined));
+
+ return (
+ <Combobox
+ id={id}
+ value={value}
+ onValueChange={(next) => {
+ setChosen(options.find((option) => option.value === next) ?? null);
+ onValueChange(next);
+ }}
+ options={options}
+ selectedOption={current}
+ disabled={disabled}
+ placeholder={placeholder}
+ searchPlaceholder="Search companies…"
+ empty={companies.isFetching ? "Searching…" : "No company matches."}
+ search={text}
+ onSearchChange={setText}
+ stale={stale}
+ variant={variant}
+ className={className}
+ />
+ );
+}
+
+export function CompanyMenuSearch({
+ none,
+ onSelect,
+ inputRef,
+}: {
+ none?: string;
+ onSelect: (companyId: string | null) => void;
+ inputRef?: Ref<HTMLInputElement>;
+}) {
+ const trpc = useTRPC();
+
+ const [query, setQuery] = useState("");
+ const [text, setText] = useSearchInput(query, setQuery);
+
+ const companies = useQuery({
+ ...trpc.companies.options.queryOptions({ q: query }),
+ placeholderData: (previous) => previous,
+ });
+
+ const stale = companies.isFetching || text.trim() !== query.trim();
+
+ return (
+ <Command
+ shouldFilter={false}
+ onKeyDown={(event) => event.stopPropagation()}
+ >
+ <CommandInput
+ ref={inputRef}
+ placeholder="Search companies…"
+ value={text}
+ onValueChange={setText}
+ autoFocus
+ />
+ <CommandList>
+ <CommandEmpty>
+ {companies.isFetching ? "Searching…" : "No company matches."}
+ </CommandEmpty>
+ <CommandGroup>
+ {none && !query.trim() ? (
+ <CommandItem
+ value="none"
+ disabled={stale}
+ onSelect={() => onSelect(null)}
+ >
+ {none}
+ </CommandItem>
+ ) : null}
+ {(companies.data ?? []).map((company) => (
+ <CommandItem
+ key={company.id}
+ value={company.id}
+ disabled={stale}
+ onSelect={() => onSelect(company.id)}
+ >
+ <span className="truncate">{company.name}</span>
+ {company.domain ? (
+ <span className="ml-auto truncate text-muted-foreground text-xs">
+ {company.domain}
+ </span>
+ ) : null}
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ );
+}
+
+export function InlineCompanyField({
+ label = "Company",
+ value,
+ onSave,
+ saving = false,
+ none,
+ company,
+}: {
+ label?: string;
+ value: string;
+ onSave: (next: string) => void;
+ saving?: boolean;
+ none?: { value: string; label: string };
+ company?: { id: string; name: string } | null;
+}) {
+ const id = useId();
+
+ return (
+ <div className={cn(PROPERTY_ROW, "items-center")}>
+ <label htmlFor={id} className={PROPERTY_LABEL}>
+ {label}
+ </label>
+ <div className="flex min-w-0 items-center gap-1.5">
+ <CompanyPicker
+ id={id}
+ value={value}
+ onValueChange={onSave}
+ none={none}
+ selected={
+ company ? { value: company.id, label: company.name } : undefined
+ }
+ disabled={saving}
+ variant="ghost"
+ className="w-full"
+ />
+ {saving ? <Spinner /> : null}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/app/components/crm/record-sheet/contact-sheet.tsx b/apps/app/components/crm/record-sheet/contact-sheet.tsx
index a72353f2..bd665b66 100644
--- a/apps/app/components/crm/record-sheet/contact-sheet.tsx
+++ b/apps/app/components/crm/record-sheet/contact-sheet.tsx
@@ -24,6 +24,7 @@ import { TableCell } from "@crm/ui/components/table";
import { useMutation, useQuery } from "@tanstack/react-query";
import { toast } from "sonner";
import { AgentPanel } from "@/components/crm/agent-panel";
+import { InlineCompanyField } from "@/components/crm/company-picker";
import { contactName } from "@/components/crm/contact-name";
import { ContactEnrichmentAction } from "@/components/crm/enrichment-actions";
import { EnrichmentIndicator } from "@/components/crm/enrichment-status";
@@ -288,7 +289,6 @@ function ContactOverview({ contact }: { contact: Contact }) {
const cache = useCrmCache();
const users = useQuery(trpc.users.list.queryOptions());
- const companies = useQuery(trpc.companies.options.queryOptions({ q: "" }));
const { applied, proposed } = factsByField(contact.facts);
@@ -382,16 +382,11 @@ function ContactOverview({ contact }: { contact: Contact }) {
onSave={(githubUrl) => save({ githubUrl })}
{...agentProps("githubUrl")}
/>
- <InlineSelectField
- label="Company"
+ <InlineCompanyField
value={contact.company?.id ?? NONE}
- options={[
- { value: NONE, label: "No company" },
- ...(companies.data ?? []).map((company) => ({
- value: company.id,
- label: company.name,
- })),
- ]}
+ company={contact.company}
+ saving={isSaving("companyId")}
+ none={{ value: NONE, label: "No company" }}
onSave={(companyId) =>
save({ companyId: companyId === NONE ? null : companyId })
}
diff --git a/apps/app/components/crm/record-sheet/deal-sheet.tsx b/apps/app/components/crm/record-sheet/deal-sheet.tsx
index 78f37749..e8228e75 100644
--- a/apps/app/components/crm/record-sheet/deal-sheet.tsx
+++ b/apps/app/components/crm/record-sheet/deal-sheet.tsx
@@ -24,6 +24,7 @@ import { formatMoney } from "@crm/ui/lib/format";
import { useMutation, useQuery } from "@tanstack/react-query";
import { toast } from "sonner";
import { AgentPanel } from "@/components/crm/agent-panel";
+import { InlineCompanyField } from "@/components/crm/company-picker";
import { contactName } from "@/components/crm/contact-name";
import { FieldsCog, RecordFields } from "@/components/crm/fields/record-fields";
import {
@@ -249,7 +250,6 @@ function DealOverview({ deal }: { deal: Deal }) {
const cache = useCrmCache();
const users = useQuery(trpc.users.list.queryOptions());
- const companies = useQuery(trpc.companies.options.queryOptions({ q: "" }));
const update = useMutation(
trpc.deals.update.mutationOptions({
@@ -332,13 +332,10 @@ function DealOverview({ deal }: { deal: Deal }) {
saving={isSaving("expectedCloseDate")}
onSave={(next) => save({ expectedCloseDate: next || null })}
/>
- <InlineSelectField
- label="Company"
+ <InlineCompanyField
value={deal.company.id}
- options={(companies.data ?? []).map((company) => ({
- value: company.id,
- label: company.name,
- }))}
+ company={deal.company}
+ saving={isSaving("companyId")}
onSave={(companyId) => save({ companyId })}
/>
<InlineSelectField
diff --git a/packages/ui/src/components/combobox.tsx b/packages/ui/src/components/combobox.tsx
new file mode 100644
index 00000000..5014a6ab
--- /dev/null
+++ b/packages/ui/src/components/combobox.tsx
@@ -0,0 +1,133 @@
+"use client";
+
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from "@crm/ui/components/command";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@crm/ui/components/popover";
+import { selectTriggerVariants } from "@crm/ui/components/select";
+import { cn } from "@crm/ui/lib/utils";
+import type { VariantProps } from "class-variance-authority";
+import { ChevronDownIcon } from "lucide-react";
+import type * as React from "react";
+import { useState } from "react";
+
+type ComboboxOption = {
+ value: string;
+ label: string;
+ hint?: string;
+ keywords?: string[];
+};
+
+function Combobox({
+ options,
+ selectedOption,
+ value,
+ onValueChange,
+ placeholder = "Select an option",
+ searchPlaceholder = "Search…",
+ empty = "Nothing matches.",
+ search,
+ onSearchChange,
+ stale,
+ size = "default",
+ variant,
+ className,
+ ...props
+}: Omit<React.ComponentProps<"button">, "onChange" | "value"> &
+ VariantProps<typeof selectTriggerVariants> & {
+ options: ComboboxOption[];
+ selectedOption?: ComboboxOption;
+ value: string;
+ onValueChange: (value: string) => void;
+ placeholder?: string;
+ searchPlaceholder?: string;
+ empty?: React.ReactNode;
+ search?: string;
+ onSearchChange?: (search: string) => void;
+ stale?: boolean;
+ size?: "sm" | "default";
+ }) {
+ const [open, setOpen] = useState(false);
+ const selected =
+ selectedOption?.value === value
+ ? selectedOption
+ : options.find((option) => option.value === value);
+
+ const close = () => {
+ setOpen(false);
+ onSearchChange?.("");
+ };
+
+ return (
+ <Popover
+ open={open}
+ onOpenChange={(next) => (next ? setOpen(true) : close())}
+ >
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ role="combobox"
+ aria-expanded={open}
+ data-slot="combobox-trigger"
+ data-size={size}
+ data-placeholder={selected ? undefined : ""}
+ className={cn(selectTriggerVariants({ variant }), className)}
+ {...props}
+ >
+ <span data-slot="select-value">{selected?.label ?? placeholder}</span>
+ <ChevronDownIcon className="pointer-events-none size-4 text-muted-foreground" />
+ </button>
+ </PopoverTrigger>
+
+ <PopoverContent
+ align="start"
+ size="fit"
+ className="w-(--radix-popover-trigger-width) min-w-64"
+ >
+ <Command shouldFilter={onSearchChange === undefined}>
+ <CommandInput
+ placeholder={searchPlaceholder}
+ value={search}
+ onValueChange={onSearchChange}
+ />
+ <CommandList>
+ <CommandEmpty>{empty}</CommandEmpty>
+ <CommandGroup>
+ {options.map((option) => (
+ <CommandItem
+ key={option.value}
+ value={option.label}
+ keywords={option.keywords}
+ disabled={stale}
+ data-checked={option.value === value}
+ onSelect={() => {
+ close();
+ onValueChange(option.value);
+ }}
+ >
+ <span className="truncate">{option.label}</span>
+ {option.hint ? (
+ <span className="ml-auto truncate text-muted-foreground text-xs">
+ {option.hint}
+ </span>
+ ) : null}
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+export { Combobox, type ComboboxOption };
diff --git a/packages/ui/src/components/data-table.tsx b/packages/ui/src/components/data-table.tsx
index 03b31b52..dd7819ab 100644
--- a/packages/ui/src/components/data-table.tsx
+++ b/packages/ui/src/components/data-table.tsx
@@ -9,6 +9,14 @@ import Column from "@carbon/icons-react/es/Column";
import Filter from "@carbon/icons-react/es/Filter";
import { Button } from "@crm/ui/components/button";
import { Checkbox } from "@crm/ui/components/checkbox";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from "@crm/ui/components/command";
import {
DropdownMenu,
DropdownMenuCheckboxItem,
@@ -19,6 +27,11 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@crm/ui/components/dropdown-menu";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@crm/ui/components/popover";
import { Spinner } from "@crm/ui/components/spinner";
import { TablePagination } from "@crm/ui/components/table-pagination";
import {
@@ -35,6 +48,7 @@ import type { TableQueryState } from "@crm/ui/lib/table-query";
import { cn } from "@crm/ui/lib/utils";
import { parseAsArrayOf, parseAsString, useQueryState } from "nuqs";
import {
+ type ComponentProps,
Fragment,
type ReactNode,
useDeferredValue,
@@ -62,6 +76,11 @@ export type DataTableFacet = {
id: string;
label: string;
options: { value: string; label: string }[];
+ searchable?: boolean;
+ search?: string;
+ onSearchChange?: (search: string) => void;
+ stale?: boolean;
+ empty?: ReactNode;
};
export type DataTableTabs = {
@@ -146,6 +165,99 @@ function SortIndicator({
);
}
+function FacetTrigger({
+ label,
+ ...props
+}: ComponentProps<typeof Button> & { label: string }) {
+ return (
+ <Button variant="outline" size="sm" className="justify-between" {...props}>
+ <span className="truncate">{label}</span>
+ <ChevronDown data-icon="inline-end" className="opacity-60" />
+ </Button>
+ );
+}
+
+function SearchableFacet({
+ facet,
+ selected,
+ activeLabel,
+ onSelect,
+}: {
+ facet: DataTableFacet;
+ selected: string;
+ activeLabel?: string;
+ onSelect: (value: string) => void;
+}) {
+ const [open, setOpen] = useState(false);
+ const [seen, setSeen] = useState<{ value: string; label: string } | null>(
+ null,
+ );
+
+ if (activeLabel && (seen?.value !== selected || seen.label !== activeLabel)) {
+ setSeen({ value: selected, label: activeLabel });
+ }
+
+ const label =
+ activeLabel ??
+ (seen?.value === selected ? seen.label : undefined) ??
+ facet.label;
+
+ const choose = (value: string) => {
+ setOpen(false);
+ facet.onSearchChange?.("");
+ onSelect(value);
+ };
+
+ return (
+ <Popover
+ open={open}
+ onOpenChange={(next) => {
+ setOpen(next);
+ if (!next) facet.onSearchChange?.("");
+ }}
+ >
+ <PopoverTrigger asChild>
+ <FacetTrigger label={label} />
+ </PopoverTrigger>
+ <PopoverContent align="start" size="fit" className="w-64">
+ <Command shouldFilter={facet.onSearchChange === undefined}>
+ <CommandInput
+ placeholder={`Search ${facet.label.toLowerCase()}…`}
+ value={facet.search}
+ onValueChange={facet.onSearchChange}
+ />
+ <CommandList>
+ <CommandEmpty>{facet.empty ?? "Nothing matches."}</CommandEmpty>
+ <CommandGroup>
+ {facet.search?.trim() ? null : (
+ <CommandItem
+ value={facet.label}
+ disabled={facet.stale}
+ data-checked={selected === "all"}
+ onSelect={() => choose("all")}
+ >
+ {facet.label}
+ </CommandItem>
+ )}
+ {facet.options.map((option) => (
+ <CommandItem
+ key={option.value}
+ value={option.label}
+ disabled={facet.stale}
+ data-checked={selected === option.value}
+ onSelect={() => choose(option.value)}
+ >
+ <span className="truncate">{option.label}</span>
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ );
+}
+
export function DataTable<TRow, TSub = unknown>({
query,
columns,
@@ -330,22 +442,23 @@ export function DataTable<TRow, TSub = unknown>({
{facets?.map((facet) => {
const selected = query.filters[facet.id] ?? "all";
const active = facet.options.find((o) => o.value === selected);
+
+ if (facet.searchable) {
+ return (
+ <SearchableFacet
+ key={facet.id}
+ facet={facet}
+ selected={selected}
+ activeLabel={active?.label}
+ onSelect={(value) => query.setFilter(facet.id, value)}
+ />
+ );
+ }
+
return (
<DropdownMenu key={facet.id}>
<DropdownMenuTrigger asChild>
- <Button
- variant="outline"
- size="sm"
- className="justify-between"
- >
- <span className="truncate">
- {active ? active.label : facet.label}
- </span>
- <ChevronDown
- data-icon="inline-end"
- className="opacity-60"
- />
- </Button>
+ <FacetTrigger label={active ? active.label : facet.label} />
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="min-w-44">
<DropdownMenuRadioGroup