Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Add async combobox for webhook link selection

Tim Wilson8a95d71c36d9
diff --git a/apps/web/app/api/links/route.ts b/apps/web/app/api/links/route.ts
index 6f405ffea1..e43c4eb568 100644
--- a/apps/web/app/api/links/route.ts
+++ b/apps/web/app/api/links/route.ts
@@ -29,6 +29,7 @@ export const GET = withWorkspace(
page,
pageSize,
userId,
+ ids,
showArchived,
withTags,
includeUser,
@@ -48,6 +49,7 @@ export const GET = withWorkspace(
page,
pageSize,
userId,
+ ids,
showArchived,
withTags,
includeUser,
diff --git a/apps/web/lib/api/links/get-links-for-workspace.ts b/apps/web/lib/api/links/get-links-for-workspace.ts
index b67cfd6034..2f1993d38a 100644
--- a/apps/web/lib/api/links/get-links-for-workspace.ts
+++ b/apps/web/lib/api/links/get-links-for-workspace.ts
@@ -14,6 +14,7 @@ export async function getLinksForWorkspace({
page,
pageSize,
userId,
+ ids,
showArchived,
withTags,
includeUser,
@@ -60,6 +61,7 @@ export async function getLinksForWorkspace({
}
: {}),
...(userId && { userId }),
+ ...(ids && { id: { in: ids } }),
},
include: {
user: includeUser,
diff --git a/apps/web/lib/swr/use-links.ts b/apps/web/lib/swr/use-links.ts
index 1738e789f5..ef32d681d8 100644
--- a/apps/web/lib/swr/use-links.ts
+++ b/apps/web/lib/swr/use-links.ts
@@ -1,7 +1,7 @@
import { useRouterStuff } from "@dub/ui";
import { fetcher } from "@dub/utils";
import { useEffect, useState } from "react";
-import useSWR from "swr";
+import useSWR, { SWRConfiguration } from "swr";
import { z } from "zod";
import { LinkWithTagsProps, UserProps } from "../types";
import { getLinksQuerySchema } from "../zod/schemas/links";
@@ -11,6 +11,7 @@ const partialQuerySchema = getLinksQuerySchema.partial();
export default function useLinks(
opts: z.infer<typeof partialQuerySchema> = {},
+ swrOpts: SWRConfiguration = {},
) {
const { id } = useWorkspace();
const { getQueryString } = useRouterStuff();
@@ -42,6 +43,7 @@ export default function useLinks(
dedupingInterval: 20000,
revalidateOnFocus: false,
keepPreviousData: true,
+ ...swrOpts,
},
);
diff --git a/apps/web/lib/zod/schemas/links.ts b/apps/web/lib/zod/schemas/links.ts
index 39f5c926cd..c00213e9e4 100644
--- a/apps/web/lib/zod/schemas/links.ts
+++ b/apps/web/lib/zod/schemas/links.ts
@@ -57,6 +57,11 @@ const LinksQuerySchema = z.object({
"The search term to filter the links by. The search term will be matched against the short link slug and the destination url.",
),
userId: z.string().optional().describe("The user ID to filter the links by."),
+ ids: z
+ .union([z.string(), z.array(z.string())])
+ .transform((v) => (Array.isArray(v) ? v : v.split(",")))
+ .optional()
+ .describe("Link IDs to filter by."),
showArchived: booleanQuerySchema
.optional()
.default("false")
diff --git a/apps/web/ui/webhooks/add-edit-webhook-form.tsx b/apps/web/ui/webhooks/add-edit-webhook-form.tsx
index 4401902f95..ab460987a7 100644
--- a/apps/web/ui/webhooks/add-edit-webhook-form.tsx
+++ b/apps/web/ui/webhooks/add-edit-webhook-form.tsx
@@ -3,18 +3,20 @@
import { clientAccessCheck } from "@/lib/api/tokens/permissions";
import useLinks from "@/lib/swr/use-links";
import useWorkspace from "@/lib/swr/use-workspace";
-import { NewWebhook, WebhookProps } from "@/lib/types";
+import { LinkProps, NewWebhook, WebhookProps } from "@/lib/types";
import {
LINK_LEVEL_WEBHOOK_TRIGGERS,
WEBHOOK_TRIGGER_DESCRIPTIONS,
WORKSPACE_LEVEL_WEBHOOK_TRIGGERS,
} from "@/lib/webhook/constants";
-import { Button, Checkbox, CopyButton, InfoTooltip } from "@dub/ui";
-import { cn } from "@dub/utils";
+import { Button, Checkbox, CopyButton, InfoTooltip, LinkLogo } from "@dub/ui";
+import { Combobox } from "@dub/ui/src";
+import { cn, getApexDomain, linkConstructor, truncate } from "@dub/utils";
import { redirect, useRouter } from "next/navigation";
import { FormEvent, useMemo, useState } from "react";
import { toast } from "sonner";
import { mutate } from "swr";
+import { useDebounce } from "use-debounce";
const defaultValues: NewWebhook = {
name: "",
@@ -34,7 +36,6 @@ export default function AddEditWebhookForm({
const router = useRouter();
const [saving, setSaving] = useState(false);
const { slug: workspaceSlug, id: workspaceId, flags, role } = useWorkspace();
- const { links } = useLinks();
if (!flags?.webhooks) {
redirect(`/${workspaceSlug}`);
@@ -252,38 +253,20 @@ export default function AddEditWebhookForm({
{enableLinkSelection || linkIds.length ? (
<div className="mt-4">
- <label htmlFor="triggers" className="flex items-center space-x-2">
- <h2 className="text-sm font-medium text-gray-900">
- Choose links we should send events for
- </h2>
- </label>
- <div className="mt-3 flex flex-col gap-4">
- <div className="max-h-[200px] min-h-[100px] overflow-y-auto pb-2">
- {links?.map((link) => (
- <div key={link.id} className="group flex h-8 gap-2 py-1">
- <Checkbox
- value={link.id}
- id={`link-${link.id}`}
- checked={linkIds.includes(link.id)}
- disabled={!canManageWebhook}
- onCheckedChange={(checked) => {
- setData({
- ...data,
- linkIds: checked
- ? [...linkIds, link.id]
- : linkIds.filter((id) => id !== link.id),
- });
- }}
- />
- <label
- htmlFor={`link-${link.id}`}
- className="select-none text-sm text-gray-600 group-hover:text-gray-800"
- >
- {link.domain}/{link.key}
- </label>
- </div>
- ))}
- </div>
+ <h2 className="text-sm font-medium text-gray-900">
+ Choose links we should send events for
+ </h2>
+ <div className="mt-3">
+ <LinksSelector
+ selectedLinkIds={linkIds}
+ setSelectedLinkIds={(ids) =>
+ setData({
+ ...data,
+ linkIds: ids,
+ })
+ }
+ disabled={!canManageWebhook}
+ />
</div>
</div>
) : null}
@@ -302,3 +285,104 @@ export default function AddEditWebhookForm({
</>
);
}
+
+const getLinkOption = (link: LinkProps) => ({
+ value: link.id,
+ label: linkConstructor({ ...link, pretty: true }),
+ icon: (
+ <LinkLogo
+ apexDomain={getApexDomain(link.url)}
+ className="h-4 w-4 sm:h-4 sm:w-4"
+ />
+ ),
+ meta: {
+ url: link.url,
+ },
+});
+
+function LinksSelector({
+ selectedLinkIds,
+ setSelectedLinkIds,
+ disabled,
+}: {
+ selectedLinkIds: string[];
+ setSelectedLinkIds: (ids: string[]) => void;
+ disabled?: boolean;
+}) {
+ const [search, setSearch] = useState("");
+ const [debouncedSearch] = useDebounce(search, 500);
+
+ const { links } = useLinks(
+ {
+ search: debouncedSearch,
+ },
+ {
+ keepPreviousData: false,
+ },
+ );
+
+ const { links: selectedLinks } = useLinks({
+ ids: selectedLinkIds,
+ });
+
+ const options = useMemo(
+ () => links?.map((link) => getLinkOption(link)),
+ [links],
+ );
+
+ const selectedOptions = useMemo(
+ () =>
+ selectedLinkIds
+ .map((id) =>
+ [...(links || []), ...(selectedLinks || [])].find((l) => l.id === id),
+ )
+ .filter(Boolean)
+ .map((l) => getLinkOption(l as LinkProps)),
+ [selectedLinkIds, links, selectedLinks],
+ );
+
+ return (
+ <Combobox
+ multiple
+ caret
+ matchTriggerWidth
+ side="top" // Since this control is near the bottom of the page, prefer top to avoid jumping
+ options={options}
+ selected={selectedOptions ?? []}
+ setSelected={(selected) => {
+ setSelectedLinkIds(selected.map(({ value: id }) => id));
+ }}
+ shouldFilter={false}
+ onSearchChange={setSearch}
+ buttonProps={{
+ disabled,
+ className: cn(
+ "h-auto py-1.5 px-2.5 w-full max-w-full text-gray-700 border-gray-300 items-start",
+ ),
+ }}
+ >
+ {selectedLinkIds.length === 0 ? (
+ <div className="py-0.5">Select links...</div>
+ ) : selectedLinks && selectedOptions ? (
+ <div className="flex flex-wrap gap-2">
+ {selectedOptions.slice(0, 10).map((option) => (
+ <span
+ key={option.value}
+ className="animate-fade-in flex min-w-0 items-center gap-1 rounded-md bg-gray-100 px-1.5 py-1 text-xs text-gray-600"
+ >
+ <LinkLogo
+ apexDomain={getApexDomain(option.meta.url)}
+ className="size-3 shrink-0 sm:size-3"
+ />
+ <span className="min-w-0 truncate">
+ {truncate(option.label, 32)}
+ </span>
+ </span>
+ ))}
+ </div>
+ ) : (
+ <div className="my-0.5 h-5 w-1/3 animate-pulse rounded bg-gray-200" />
+ )}
+ </Combobox>
+ );
+}
diff --git a/packages/ui/src/combobox/index.tsx b/packages/ui/src/combobox/index.tsx
index 96ce998307..dac4ab2a92 100644
--- a/packages/ui/src/combobox/index.tsx
+++ b/packages/ui/src/combobox/index.tsx
@@ -54,6 +54,8 @@ export type ComboboxProps<
side?: PopoverProps["side"];
open?: boolean;
onOpenChange?: (open: boolean) => void;
+ onSearchChange?: (search: string) => void;
+ shouldFilter?: boolean;
optionClassName?: string;
matchTriggerWidth?: boolean;
}>;
@@ -82,6 +84,8 @@ export function Combobox({
side,
open,
onOpenChange,
+ onSearchChange,
+ shouldFilter = true,
optionClassName,
matchTriggerWidth,
children,
@@ -127,14 +131,15 @@ export function Combobox({
};
const sortOptions = useCallback(
- (options: ComboboxOption[]) => {
- return [...options].sort((a, b) => {
- const aSelected = selected.some((s) => s.value === a.value);
- const bSelected = selected.some((s) => s.value === b.value);
- if (aSelected && !bSelected) return -1;
- if (!aSelected && bSelected) return 1;
- return 0;
- });
+ (options: ComboboxOption[], search: string) => {
+ return search === ""
+ ? [
+ ...selected,
+ ...options.filter(
+ (o) => selected.findIndex((s) => s.value === o.value) === -1,
+ ),
+ ]
+ : options;
},
[selected],
);
@@ -142,10 +147,10 @@ export function Combobox({
// Actually sort the options when needed
useEffect(() => {
if (shouldSortOptions) {
- setSortedOptions(options ? sortOptions(options) : options);
+ setSortedOptions(options ? sortOptions(options, search) : options);
setShouldSortOptions(false);
}
- }, [shouldSortOptions, options, sortOptions]);
+ }, [shouldSortOptions, options, sortOptions, search]);
// Sort options when the options prop changes
useEffect(() => {
@@ -160,6 +165,8 @@ export function Combobox({
setShouldSortOptions(true);
}, [isOpen]);
+ useEffect(() => onSearchChange?.(search), [search]);
+
return (
<Popover
openPopover={isOpen}
@@ -180,7 +187,7 @@ export function Combobox({
style={{ transform: "translateZ(0)" }} // Fixes overflow on some browsers
transition={{ ease: "easeInOut", duration: 0.1 }}
>
- <Command loop>
+ <Command loop shouldFilter={shouldFilter}>
<div className="flex items-center overflow-hidden rounded-t-lg border-b border-gray-200">
<CommandInput
placeholder={searchPlaceholder}
@@ -249,12 +256,18 @@ export function Combobox({
</div>
</CommandItem>
)}
- <CommandEmpty className="flex h-12 items-center justify-center text-sm text-gray-500">
- {emptyState ? emptyState : "No matches"}
- </CommandEmpty>
+ {shouldFilter ? (
+ <CommandEmpty className="flex h-12 items-center justify-center text-sm text-gray-500">
+ {emptyState ? emptyState : "No matches"}
+ </CommandEmpty>
+ ) : sortedOptions.length === 0 ? (
+ <div className="flex h-12 items-center justify-center text-sm text-gray-500">
+ {emptyState ? emptyState : "No matches"}
+ </div>
+ ) : null}
</>
) : (
- // undefined - loading state
+ // undefined data / explicit loading state
<Command.Loading>
<div className="flex h-12 items-center justify-center">
<LoadingSpinner />