The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add tag selection/creation
Tim Wilson6fb837ce805b
diff --git a/apps/web/ui/modals/add-edit-link-modal-new/constants.ts b/apps/web/ui/modals/add-edit-link-modal-new/constants.tsindex 1c3276cfdf..d180b045a9 100644--- a/apps/web/ui/modals/add-edit-link-modal-new/constants.ts+++ b/apps/web/ui/modals/add-edit-link-modal-new/constants.ts@@ -86,7 +86,7 @@ export const MOBILE_MORE_ITEMS = [description:"Target your links to specific audiences based on their location, device, or browser.",learnMoreUrl: "https://dub.co/help/article/geo-targeting",- shortcutKey: "t",+ shortcutKey: "x",enabled: (data: LinkFormData) =>Boolean(data.ios || data.android || Object.keys(data.geo || {}).length > 0,diff --git a/apps/web/ui/modals/add-edit-link-modal-new/index.tsx b/apps/web/ui/modals/add-edit-link-modal-new/index.tsxindex 329fe3fac8..90c891dfd5 100644--- a/apps/web/ui/modals/add-edit-link-modal-new/index.tsx+++ b/apps/web/ui/modals/add-edit-link-modal-new/index.tsx@@ -53,6 +53,7 @@ import { MoreDropdown } from "./more-dropdown";import { OptionsList } from "./options-list";import { usePasswordModal } from "./password-modal";import { QRCodePreview } from "./qr-code-preview";+import { TagSelect } from "./tag-select";import { useTargetingModal } from "./targeting-modal";import { useMetatags } from "./use-metatags";import { UTMBuilder } from "./utm-builder";@@ -444,6 +445,7 @@ function AddEditLinkModalInner({</div><div className="flex items-center justify-between border-t border-gray-100 bg-gray-50 p-4"><div className="flex items-center gap-2">+ <TagSelect /><div className="flex items-center gap-2 max-sm:hidden"><ExpirationButton /><TargetingButton />diff --git a/apps/web/ui/modals/add-edit-link-modal-new/tag-select.tsx b/apps/web/ui/modals/add-edit-link-modal-new/tag-select.tsxnew file mode 100644index 0000000000..1b983ba9c8--- /dev/null+++ b/apps/web/ui/modals/add-edit-link-modal-new/tag-select.tsx@@ -0,0 +1,152 @@+import useTags from "@/lib/swr/use-tags";+import { TagProps } from "@/lib/types";+import { COLORS_LIST } from "@/ui/links/tag-badge";+import { Combobox, useKeyboardShortcut } from "@dub/ui";+import { cn } from "@dub/utils";+import { useContext, useMemo, useState } from "react";+import { useFormContext } from "react-hook-form";+import { toast } from "sonner";+import { mutate } from "swr";+import { LinkFormData, LinkModalContext } from ".";++export function TagSelect() {+ const { workspaceId } = useContext(LinkModalContext);+ const { tags: availableTags } = useTags();++ const { watch, setValue } = useFormContext<LinkFormData>();+ const tags = watch("tags");++ const [isOpen, setIsOpen] = useState(false);++ const createTag = async (tag: string) => {+ const res = await fetch(`/api/tags?workspaceId=${workspaceId}`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ tag }),+ });++ if (res.ok) {+ const newTag = await res.json();+ setValue("tags", [...tags, newTag]);+ toast.success(`Successfully created tag!`);+ setIsOpen(false);+ await mutate(`/api/tags?workspaceId=${workspaceId}`);+ return true;+ } else {+ const { error } = await res.json();+ toast.error(error.message);+ }++ return false;+ };++ const options = useMemo(+ () =>+ availableTags?.map((tag) => ({+ label: tag.name,+ value: tag.id,+ icon: <TagIcon tags={[tag]} />,+ meta: {+ color: tag.color,+ },+ })),+ [availableTags],+ );++ const selectedTags = useMemo(+ () =>+ tags+ .map(({ id }) => options?.find(({ value }) => value === id)!)+ .filter(Boolean),+ [tags, options],+ );++ useKeyboardShortcut("t", () => setIsOpen(true), { modal: true });++ return (+ <Combobox+ multiple+ selected={selectedTags}+ setSelected={(tags) => {+ const selectedIds = tags.map(({ value }) => value);+ setValue(+ "tags",+ selectedIds.map((id) => availableTags?.find((t) => t.id === id)),+ );+ }}+ options={options}+ icon={<TagIcon tags={selectedTags.map(({ meta }) => meta)} />}+ placeholder="Tags"+ searchPlaceholder="Search or add tags..."+ buttonProps={{ className: "h-9 px-2.5 w-fit font-medium text-gray-700" }}+ onCreate={(search) => createTag(search)}+ open={isOpen}+ onOpenChange={setIsOpen}+ >+ {selectedTags.length > 0+ ? selectedTags.length === 1+ ? selectedTags[0].label+ : `${selectedTags.length} Tags`+ : "Tags"}+ </Combobox>+ );+}++function TagIcon({ tags }: { tags: Pick<TagProps, "color">[] }) {+ return (+ <svg+ height="18"+ width="18"+ viewBox="0 0 18 18"+ xmlns="http://www.w3.org/2000/svg"+ className={cn(+ "size-4",+ tags.length > 0 &&+ COLORS_LIST.find(({ color }) => color === tags[0].color)?.css,+ "bg-transparent",+ tags.length <= 1 && "-translate-y-px",+ )}+ >+ <g fill="currentColor">+ {tags.length > 0 && (+ <path+ d="M1.75 4.25H7.336C7.601 4.25 7.856 4.355 8.043 4.543L13.836 10.336C14.617 11.117 14.617 12.383 13.836 13.164L10.664 16.336C9.883 17.117 8.617 17.117 7.836 16.336L2.043 10.543C1.855 10.355 1.75 10.101 1.75 9.836V4.25Z"+ fill="currentColor"+ fillOpacity={0.15}+ stroke="none"+ />+ )}+ <path+ d="M1.75 4.25H7.336C7.601 4.25 7.856 4.355 8.043 4.543L13.836 10.336C14.617 11.117 14.617 12.383 13.836 13.164L10.664 16.336C9.883 17.117 8.617 17.117 7.836 16.336L2.043 10.543C1.855 10.355 1.75 10.101 1.75 9.836V4.25Z"+ fill="none"+ stroke="currentColor"+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth="1.5"+ />++ {tags.length > 1 && (+ <path+ d="M3.25 1.75V1.25H8.836C9.101 1.25 9.356 1.355 9.543 1.543L15.336 7.336C15.768 7.768 15.961 8.348 15.915 8.913"+ fill="none"+ stroke="currentColor"+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth="1.5"+ className={cn(+ COLORS_LIST.find(({ color }) => color === tags[1].color)?.css,+ "bg-transparent",+ )}+ />+ )}+ <path+ d="M5.25 9C5.94036 9 6.5 8.44036 6.5 7.75C6.5 7.05964 5.94036 6.5 5.25 6.5C4.55964 6.5 4 7.05964 4 7.75C4 8.44036 4.55964 9 5.25 9Z"+ fill="currentColor"+ stroke="none"+ />+ </g>+ </svg>+ );+}diff --git a/apps/web/ui/modals/add-edit-link-modal-new/targeting-modal.tsx b/apps/web/ui/modals/add-edit-link-modal-new/targeting-modal.tsxindex 8c49d152fa..0de57784d8 100644--- a/apps/web/ui/modals/add-edit-link-modal-new/targeting-modal.tsx+++ b/apps/web/ui/modals/add-edit-link-modal-new/targeting-modal.tsx@@ -91,14 +91,14 @@ function TargetingModal({content={<div className="px-2 py-1 text-xs text-gray-700">Press{" "}- <strong className="font-medium text-gray-950">T</strong> to+ <strong className="font-medium text-gray-950">X</strong> toopen this quickly</div>}side="right"><kbd className="flex size-6 cursor-default items-center justify-center gap-1 rounded-md border border-gray-200 font-sans text-xs text-gray-950">- T+ X</kbd></Tooltip></div>@@ -311,7 +311,7 @@ function TargetingButton({const { watch } = useFormContext<LinkFormData>();const [ios, android, geo] = watch(["ios", "android", "geo"]);- useKeyboardShortcut("t", () => setShowTargetingModal(true), {+ useKeyboardShortcut("x", () => setShowTargetingModal(true), {modal: true,});diff --git a/packages/ui/src/combobox/index.tsx b/packages/ui/src/combobox/index.tsxnew file mode 100644index 0000000000..56b28cbb53--- /dev/null+++ b/packages/ui/src/combobox/index.tsx@@ -0,0 +1,307 @@+import { cn, truncate } from "@dub/utils";+import { Command, CommandEmpty, CommandInput, CommandItem } from "cmdk";+import {+ isValidElement,+ PropsWithChildren,+ ReactNode,+ useEffect,+ useRef,+ useState,+} from "react";+import { AnimatedSizeContainer } from "../animated-size-container";+import { Button, ButtonProps } from "../button";+import { useMediaQuery, useScrollProgress } from "../hooks";+import {+ CheckboxCheckedFill,+ CheckboxUnchecked,+ Icon,+ LoadingSpinner,+ Plus,+} from "../icons";+import { Popover } from "../popover";++export type ComboboxOption<TMeta = any> = {+ label: string;+ value: string;+ icon?: Icon | ReactNode;+ meta?: TMeta;+};++export type ComboboxProps<+ TMultiple extends boolean | undefined,+ TMeta extends any,+> = PropsWithChildren<{+ multiple?: TMultiple;+ selected: TMultiple extends true+ ? ComboboxOption<TMeta>[]+ : ComboboxOption<TMeta> | null;+ setSelected: TMultiple extends true+ ? (tags: ComboboxOption<TMeta>[]) => void+ : (tag: ComboboxOption<TMeta> | null) => void;+ options?: ComboboxOption<TMeta>[];+ icon?: Icon | ReactNode;+ placeholder?: string;+ searchPlaceholder?: string;+ emptyState?: ReactNode;+ createLabel?: (search: string) => ReactNode;+ onCreate?: (search: string) => Promise<boolean>;+ buttonProps?: ButtonProps;+ open?: boolean;+ onOpenChange?: (open: boolean) => void;+}>;++function isMultipleSelection(+ multiple: boolean | undefined,+ setSelected: any,+): setSelected is (tags: ComboboxOption[]) => void {+ return multiple === true;+}++export function Combobox({+ multiple,+ selected: selectedProp,+ setSelected,+ options,+ icon: Icon,+ placeholder = "Select...",+ searchPlaceholder = "Search...",+ emptyState,+ createLabel,+ onCreate,+ buttonProps,+ open,+ onOpenChange,+ children,+}: ComboboxProps<boolean | undefined, any>) {+ const isMultiple = isMultipleSelection(multiple, setSelected);++ // Ensure selectedProp is an array+ const selected = Array.isArray(selectedProp)+ ? selectedProp+ : selectedProp+ ? [selectedProp]+ : [];++ const { isMobile } = useMediaQuery();++ const [isOpenInternal, setIsOpenInternal] = useState(false);+ const isOpen = open ?? isOpenInternal;+ const setIsOpen = onOpenChange ?? setIsOpenInternal;++ const [search, setSearch] = useState("");+ const [isCreating, setIsCreating] = useState(false);++ const handleSelect = (option: ComboboxOption) => {+ if (isMultiple) {+ const isAlreadySelected = selected.some(+ ({ value }) => value === option.value,+ );+ setSelected(+ isAlreadySelected+ ? selected.filter(({ value }) => value !== option.value)+ : [...selected, option],+ );+ } else+ setSelected(+ selected.length && selected[0]?.value === option.value ? null : option,+ );+ };++ useEffect(() => {+ if (!isOpen) setSearch("");+ }, [isOpen]);++ return (+ <Popover+ openPopover={isOpen}+ setOpenPopover={setIsOpen}+ align="start"+ side="top"+ onWheel={(e) => {+ // Allows scrolling to work when the popover's in a modal+ e.stopPropagation();+ }}+ content={+ <AnimatedSizeContainer+ width={!isMobile}+ height+ className="rounded-[inherit]"+ style={{ transform: "translateZ(0)" }} // Fixes overflow on some browsers+ transition={{ ease: "easeInOut", duration: 0.1 }}+ >+ <Command loop>+ <div className="flex items-center overflow-hidden rounded-t-lg border-b border-gray-200">+ <CommandInput+ placeholder={searchPlaceholder}+ value={search}+ onValueChange={setSearch}+ className="grow border-0 py-3 pl-4 pr-2 outline-none placeholder:text-gray-400 focus:ring-0 sm:text-sm"+ onKeyDown={(e) => {+ if (+ e.key === "Escape" ||+ (e.key === "Backspace" && !search)+ ) {+ e.preventDefault();+ e.stopPropagation();+ setIsOpen(false);+ }+ }}+ />+ <kbd className="mr-2 hidden shrink-0 rounded bg-gray-200 px-2 py-0.5 text-xs font-light text-gray-500 md:block">+ T+ </kbd>+ </div>+ <Scroll>+ <Command.List+ className={cn("flex w-full min-w-[100px] flex-col gap-1 p-1")}+ >+ {options !== undefined ? (+ <>+ {options.map((option) => (+ <Option+ key={`${option.label}, ${option.value}`}+ option={option}+ multiple={isMultiple}+ selected={selected.some(+ ({ value }) => value === option.value,+ )}+ onSelect={() => handleSelect(option)}+ />+ ))}+ {search.length > 0 && onCreate && (+ <CommandItem+ className={cn(+ "flex cursor-pointer items-center gap-3 whitespace-nowrap rounded-md px-3 py-2 text-left text-sm text-gray-700",+ "data-[selected=true]:bg-gray-100",+ )}+ onSelect={async () => {+ setIsCreating(true);+ const success = await onCreate?.(search);+ if (success) {+ setSearch("");+ setIsOpen(false);+ }+ setIsCreating(false);+ }}+ >+ {isCreating ? (+ <LoadingSpinner className="size-4 shrink-0" />+ ) : (+ <Plus className="size-4 shrink-0" />+ )}+ <div className="grow">+ {createLabel?.(search) || `Create "${search}"`}+ </div>+ </CommandItem>+ )}+ <CommandEmpty className="flex h-12 items-center justify-center text-sm text-gray-500">+ {emptyState ? emptyState : "No matches"}+ </CommandEmpty>+ </>+ ) : (+ // undefined - loading state+ <Command.Loading>+ <div className="flex h-12 items-center justify-center">+ <LoadingSpinner />+ </div>+ </Command.Loading>+ )}+ </Command.List>+ </Scroll>+ </Command>+ </AnimatedSizeContainer>+ }+ >+ <Button+ variant="secondary"+ {...buttonProps}+ className={cn(buttonProps?.className, "flex items-center gap-2")}+ text={+ children ||+ selected.map((option) => option.label).join(", ") ||+ placeholder+ }+ icon={+ Icon ? (+ isReactNode(Icon) ? (+ Icon+ ) : (+ <Icon className="size-4" />+ )+ ) : undefined+ }+ />+ </Popover>+ );+}++const Scroll = ({ children }: PropsWithChildren) => {+ const ref = useRef<HTMLDivElement>(null);++ const { scrollProgress, updateScrollProgress } = useScrollProgress(ref);++ return (+ <>+ <div+ className="scrollbar-hide max-h-[min(50vh,190px)] w-screen overflow-y-scroll sm:w-auto"+ ref={ref}+ onScroll={updateScrollProgress}+ >+ {children}+ </div>+ {/* Bottom scroll fade */}+ <div+ className="pointer-events-none absolute bottom-0 left-0 hidden h-16 w-full bg-gradient-to-t from-white sm:block"+ style={{ opacity: 1 - Math.pow(scrollProgress, 2) }}+ ></div>+ </>+ );+};++function Option({+ option,+ onSelect,+ multiple,+ selected,+}: {+ option: ComboboxOption;+ onSelect: () => void;+ multiple: boolean;+ selected: boolean;+}) {+ return (+ <Command.Item+ className={cn(+ "flex cursor-pointer items-center gap-3 whitespace-nowrap rounded-md px-3 py-2 text-left text-sm",+ "data-[selected=true]:bg-gray-100",+ )}+ onSelect={onSelect}+ value={option.label + option?.value}+ >+ {multiple && (+ <div className="shrink-0 text-gray-600">+ {selected ? (+ <CheckboxCheckedFill className="size-4 text-gray-600" />+ ) : (+ <CheckboxUnchecked className="size-4 text-gray-400" />+ )}+ </div>+ )}+ <div className="flex items-center gap-1">+ {option.icon && (+ <span className="shrink-0 text-gray-600">+ {isReactNode(option.icon) ? (+ option.icon+ ) : (+ <option.icon className="h-4 w-4" />+ )}+ </span>+ )}+ {truncate(option.label, 48)}+ </div>+ </Command.Item>+ );+}++const isReactNode = (element: any): element is ReactNode =>+ isValidElement(element);diff --git a/packages/ui/src/icons/nucleo/checkbox-checked-fill.tsx b/packages/ui/src/icons/nucleo/checkbox-checked-fill.tsxnew file mode 100644index 0000000000..0f42b270a1--- /dev/null+++ b/packages/ui/src/icons/nucleo/checkbox-checked-fill.tsx@@ -0,0 +1,20 @@+import { SVGProps } from "react";++export function CheckboxCheckedFill(props: SVGProps<SVGSVGElement>) {+ return (+ <svg+ height="18"+ width="18"+ viewBox="0 0 18 18"+ xmlns="http://www.w3.org/2000/svg"+ {...props}+ >+ <g fill="currentColor">+ <path+ d="M13.25,2H4.75c-1.517,0-2.75,1.233-2.75,2.75V13.25c0,1.517,1.233,2.75,2.75,2.75H13.25c1.517,0,2.75-1.233,2.75-2.75V4.75c0-1.517-1.233-2.75-2.75-2.75Zm-.407,4.708l-4.25,5.5c-.136,.176-.343,.283-.565,.291-.01,0-.019,0-.028,0-.212,0-.415-.09-.558-.248l-2.25-2.5c-.277-.308-.252-.782,.056-1.06,.309-.276,.782-.252,1.06,.056l1.648,1.832,3.701-4.789c.252-.328,.726-.388,1.052-.135,.328,.253,.388,.724,.135,1.052Z"+ fill="currentColor"+ />+ </g>+ </svg>+ );+}diff --git a/packages/ui/src/icons/nucleo/checkbox-unchecked.tsx b/packages/ui/src/icons/nucleo/checkbox-unchecked.tsxnew file mode 100644index 0000000000..5baca6df74--- /dev/null+++ b/packages/ui/src/icons/nucleo/checkbox-unchecked.tsx@@ -0,0 +1,29 @@+import { SVGProps } from "react";++export function CheckboxUnchecked(props: SVGProps<SVGSVGElement>) {+ return (+ <svg+ height="18"+ width="18"+ viewBox="0 0 18 18"+ xmlns="http://www.w3.org/2000/svg"+ {...props}+ >+ <g fill="currentColor">+ <rect+ height="12.5"+ width="12.5"+ fill="none"+ rx="2"+ ry="2"+ stroke="currentColor"+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth="1.5"+ x="2.75"+ y="2.75"+ />+ </g>+ </svg>+ );+}diff --git a/packages/ui/src/icons/nucleo/index.ts b/packages/ui/src/icons/nucleo/index.tsindex dcadb1173d..1f693c7e57 100644--- a/packages/ui/src/icons/nucleo/index.ts+++ b/packages/ui/src/icons/nucleo/index.ts@@ -15,6 +15,8 @@ export * from "./chart-activity2";export * from "./chart-line";export * from "./check";export * from "./check2";+export * from "./checkbox-checked-fill";+export * from "./checkbox-unchecked";export * from "./circle-check";export * from "./circle-dotted";export * from "./circle-half-dotted-clock";@@ -72,6 +74,7 @@ export * from "./paintbrush";export * from "./pen-writing";export * from "./pen2";export * from "./photo";+export * from "./plus";export * from "./pyramid";export * from "./qrcode";export * from "./receipt2";diff --git a/packages/ui/src/icons/nucleo/plus.tsx b/packages/ui/src/icons/nucleo/plus.tsxnew file mode 100644index 0000000000..40b8a76517--- /dev/null+++ b/packages/ui/src/icons/nucleo/plus.tsx@@ -0,0 +1,38 @@+import { SVGProps } from "react";++export function Plus(props: SVGProps<SVGSVGElement>) {+ return (+ <svg+ height="18"+ width="18"+ viewBox="0 0 18 18"+ xmlns="http://www.w3.org/2000/svg"+ {...props}+ >+ <g fill="currentColor">+ <line+ fill="none"+ stroke="currentColor"+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth="1.5"+ x1="9"+ x2="9"+ y1="3.25"+ y2="14.75"+ />+ <line+ fill="none"+ stroke="currentColor"+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth="1.5"+ x1="3.25"+ x2="14.75"+ y1="9"+ y2="9"+ />+ </g>+ </svg>+ );+}diff --git a/packages/ui/src/index.tsx b/packages/ui/src/index.tsxindex 868aec4925..530957ace6 100644--- a/packages/ui/src/index.tsx+++ b/packages/ui/src/index.tsx@@ -10,6 +10,7 @@ export * from "./button";export * from "./card-list";export * from "./carousel";export * from "./checkbox";+export * from "./combobox";export * from "./date-picker";export * from "./file-upload";export * from "./filter";diff --git a/packages/ui/src/popover.tsx b/packages/ui/src/popover.tsxindex 512554a005..692dc88c64 100644--- a/packages/ui/src/popover.tsx+++ b/packages/ui/src/popover.tsx@@ -2,13 +2,14 @@import { cn } from "@dub/utils";import * as PopoverPrimitive from "@radix-ui/react-popover";-import { PropsWithChildren, ReactNode } from "react";+import { PropsWithChildren, ReactNode, WheelEventHandler } from "react";import { Drawer } from "vaul";import { useMediaQuery } from "./hooks";export type PopoverProps = PropsWithChildren<{content: ReactNode | string;align?: "center" | "start" | "end";+ side?: "bottom" | "top" | "left" | "right";openPopover: boolean;setOpenPopover: (open: boolean) => void;mobileOnly?: boolean;@@ -16,12 +17,14 @@ export type PopoverProps = PropsWithChildren<{collisionBoundary?: Element | Element[];sticky?: "partial" | "always";onEscapeKeyDown?: (event: KeyboardEvent) => void;+ onWheel?: WheelEventHandler;}>;export function Popover({children,content,align = "center",+ side = "bottom",openPopover,setOpenPopover,mobileOnly,@@ -29,6 +32,7 @@ export function Popover({collisionBoundary,sticky,onEscapeKeyDown,+ onWheel,}: PopoverProps) {const { isMobile } = useMediaQuery();@@ -66,6 +70,7 @@ export function Popover({<PopoverPrimitive.ContentsideOffset={8}align={align}+ side={side}className={cn("animate-slide-up-fade z-50 items-center rounded-lg border border-gray-200 bg-white drop-shadow-lg sm:block",popoverContentClassName,@@ -73,6 +78,7 @@ export function Popover({sticky={sticky}collisionBoundary={collisionBoundary}onEscapeKeyDown={onEscapeKeyDown}+ onWheel={onWheel}>{content}</PopoverPrimitive.Content>