The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Start adding new filter UI
Tim Wilson4311b5ceae29
diff --git a/apps/web/ui/analytics/toggle.tsx b/apps/web/ui/analytics/toggle.tsxindex c8ed4637e6..39a62f5038 100644--- a/apps/web/ui/analytics/toggle.tsx+++ b/apps/web/ui/analytics/toggle.tsx@@ -1,11 +1,14 @@import { INTERVAL_DATA, INTERVAL_DISPLAYS } from "@/lib/analytics/constants";import { validDateRangeForPlan } from "@/lib/analytics/utils";+import useDomains from "@/lib/swr/use-domains";+import useTags from "@/lib/swr/use-tags";import useWorkspace from "@/lib/swr/use-workspace";import {BlurImage,DatePickerContext,DateRangePicker,ExpandingArrow,+ Filter,TooltipContent,useRouterStuff,useScroll,@@ -20,22 +23,95 @@ import {linkConstructor,} from "@dub/utils";import { subDays } from "date-fns";-import { useContext } from "react";+import { Globe, MousePointerClick, QrCode, Tag } from "lucide-react";+import { useContext, useMemo } from "react";import { AnalyticsContext } from ".";+import { COLORS_LIST } from "../links/tag-badge";import ExportButton from "./export-button";-import FilterBar from "./filter-bar";import SharePopover from "./share-popover";export default function Toggle() {const { plan } = useWorkspace();const { basePath, domain, key, url, admin, demo, start, end } =useContext(AnalyticsContext);- const { queryParams } = useRouterStuff();+ const { tags } = useTags();+ const { allWorkspaceDomains: domains } = useDomains();+ const { queryParams, searchParamsObj } = useRouterStuff();const scrolled = useScroll(80);const isPublicStatsPage = basePath.startsWith("/stats");+ const filters = useMemo(+ () => [+ {+ key: "domain",+ icon: Globe,+ label: "Domain",+ options: domains.map((domain) => ({+ value: domain.slug,+ label: domain.slug,+ icon: (+ <BlurImage+ src={`${GOOGLE_FAVICON_URL}${domain.slug}`}+ alt={domain.slug}+ className="h-4 w-4 rounded-full"+ width={16}+ height={16}+ />+ ),+ })),+ },+ {+ key: "tagId",+ icon: Tag,+ label: "Tag",+ options:+ tags?.map((tag) => ({+ value: tag.id,+ icon: (+ <div+ className={cn(+ "h-5 w-5 rounded-full p-1",+ COLORS_LIST.find(({ color }) => color === tag.color)?.css,+ )}+ >+ <Tag className="h-3 w-3" />+ </div>+ ),+ label: tag.name,+ })) ?? null,+ },+ {+ key: "qr",+ icon: MousePointerClick,+ label: "Trigger",+ options: [+ {+ value: false,+ label: "Link click",+ icon: MousePointerClick,+ },+ {+ value: true,+ label: "QR Scan",+ icon: QrCode,+ },+ ],+ },+ ],+ [domains, tags],+ );++ const activeFilters = useMemo(() => {+ const { domain, tagId, qr } = searchParamsObj;+ return [+ ...(domain ? [{ key: "domain", value: domain }] : []),+ ...(tagId ? [{ key: "tagId", value: tagId }] : []),+ ...(qr ? [{ key: "qr", value: qr === "true" }] : []),+ ];+ }, [searchParamsObj]);+return (<divclassName={cn("sticky top-[6.85rem] z-10 mb-5 bg-gray-50 py-3 md:py-3", {@@ -98,7 +174,24 @@ export default function Toggle() {"w-full md:w-auto": key,})}>- {!isPublicStatsPage && !key && !admin && !demo && <FilterBar />}+ {!isPublicStatsPage && !key && !admin && !demo && (+ <Filter.Select+ filters={filters}+ activeFilters={activeFilters}+ onSelect={(key, value) =>+ queryParams({+ set: {+ [key]: value,+ },+ })+ }+ onRemove={(key) =>+ queryParams({+ del: key,+ })+ }+ />+ )}{!isPublicStatsPage && key && <SharePopover />}<divclassName={cn("flex w-full items-center gap-2", {diff --git a/packages/ui/src/animated-size-container.tsx b/packages/ui/src/animated-size-container.tsxnew file mode 100644index 0000000000..6a15e45d67--- /dev/null+++ b/packages/ui/src/animated-size-container.tsx@@ -0,0 +1,61 @@+import { cn } from "@dub/utils";+import { motion } from "framer-motion";+import {+ ComponentPropsWithoutRef,+ PropsWithChildren,+ forwardRef,+ useRef,+} from "react";+import { useResizeObserver } from "./hooks";++type AnimatedSizeContainerProps = PropsWithChildren<{+ width?: boolean;+ height?: boolean;+}> &+ Omit<ComponentPropsWithoutRef<typeof motion.div>, "animate" | "children">;++/**+ * A container with animated width and height (each optional) based on children dimensions+ */+const AnimatedSizeContainer = forwardRef<+ HTMLDivElement,+ AnimatedSizeContainerProps+>(+ (+ {+ width = false,+ height = false,+ className,+ transition,+ children,+ }: AnimatedSizeContainerProps,+ forwardedRef,+ ) => {+ const containerRef = useRef<HTMLDivElement>(null);+ const resizeObserverEntry = useResizeObserver(containerRef);++ return (+ <motion.div+ ref={forwardedRef}+ className={cn("overflow-hidden", className)}+ animate={{+ width: width+ ? resizeObserverEntry?.contentRect?.width ?? "auto"+ : "auto",+ height: height+ ? resizeObserverEntry?.contentRect?.height ?? "auto"+ : "auto",+ }}+ transition={transition ?? { type: "spring", duration: 0.3 }}+ >+ <div ref={containerRef} className="h-max w-max">+ {children}+ </div>+ </motion.div>+ );+ },+);++AnimatedSizeContainer.displayName = "AnimatedSizeContainer";++export { AnimatedSizeContainer };diff --git a/packages/ui/src/filter.tsx b/packages/ui/src/filter.tsxnew file mode 100644index 0000000000..6a844e97c6--- /dev/null+++ b/packages/ui/src/filter.tsx@@ -0,0 +1,304 @@+import { cn } from "@dub/utils";+import { Check, ChevronDown, ListFilter, LucideIcon } from "lucide-react";+import {+ ReactNode,+ isValidElement,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import { AnimatedSizeContainer } from "./animated-size-container";+import { LoadingSpinner } from "./icons";+import { Popover } from "./popover";++type Filter = {+ key: string;+ icon: LucideIcon | ReactNode;+ label: string;+ options: FilterOption[] | null;+};++type FilterOption = {+ value: any;+ icon: LucideIcon | ReactNode;+ label: string;+ right?: ReactNode;+};++type FilterProps = {+ filters: Filter[];+ onSelect: (key: string, value: string) => void;+ onRemove: (key: string) => void;+ activeFilters?: {+ key: Filter["key"];+ value: FilterOption["value"];+ }[];+ children?: ReactNode;+ className?: string;+};++function Select({+ filters,+ onSelect,+ onRemove,+ activeFilters,+ children,+ className,+}: FilterProps) {+ // Track main list container/dimensions to maintain size for loading spinner+ const mainListContainer = useRef<HTMLDivElement>(null);+ const mainListDimensions = useRef<{+ width: number;+ height: number;+ }>();++ const [isOpen, setIsOpen] = useState(false);+ const [search, setSearch] = useState("");+ const [selectedFilterKey, setSelectedFilterKey] = useState<+ Filter["key"] | null+ >(null);++ const reset = useCallback(() => {+ setSearch("");+ setSelectedFilterKey(null);+ }, []);++ // Reset state when closed+ useEffect(() => {+ if (!isOpen) reset();+ }, [isOpen]);++ // The currently selected filter to display options for+ const selectedFilter = selectedFilterKey+ ? filters.find(({ key }) => key === selectedFilterKey)+ : null;++ const openFilter = useCallback((key: Filter["key"]) => {+ if (mainListContainer.current) {+ mainListDimensions.current = {+ width: mainListContainer.current.scrollWidth,+ height: mainListContainer.current.scrollHeight,+ };+ }++ setSearch("");+ setSelectedFilterKey(key);+ }, []);++ const selectOption = useCallback(+ (value: FilterOption["value"]) => {+ if (!selectedFilter) return;++ activeFilters?.find(({ key }) => key === selectedFilterKey)?.value ===+ value+ ? onRemove(selectedFilter.key)+ : onSelect(selectedFilter.key, value);++ setIsOpen(false);+ },+ [activeFilters, selectedFilter],+ );++ // Filters with options that match the search+ const filteredFilters = useMemo(+ () =>+ filters.filter(+ ({ label, options }) =>+ (!search || label.toLowerCase().includes(search.toLowerCase())) &&+ options?.length !== 0,+ ),+ [filters, search],+ );++ // The currently highlighted filter that will be selected on enter press+ const highlightedFilterKey = useMemo(+ () =>+ !selectedFilterKey && search.length > 0 && filteredFilters.length+ ? filteredFilters[0].key+ : null,+ [search, filteredFilters],+ );++ // Options that match the search+ const filteredOptions = useMemo(+ () =>+ selectedFilter+ ? search+ ? selectedFilter.options?.filter(({ label }) =>+ label.toLowerCase().includes(search.toLowerCase()),+ )+ : selectedFilter.options+ : null,+ [selectedFilter, search],+ );++ // The currently highlighted option that will be selected on enter press+ const highlightedOptionValue = useMemo(+ () =>+ selectedFilter && search && filteredOptions?.length+ ? filteredOptions[0].value+ : null,+ [filteredOptions, search],+ );++ return (+ <Popover+ openPopover={isOpen}+ setOpenPopover={setIsOpen}+ onEscapeKeyDown={(e) => {+ selectedFilterKey ? reset() : setIsOpen(false);+ e.preventDefault();+ }}+ content={+ <AnimatedSizeContainer width height>+ <div>+ <input+ type="text"+ className="rounded-t-lg border-0 border-b border-gray-200 px-4 py-3 text-sm ring-0 placeholder:text-gray-400 focus:border-gray-200 focus:ring-0"+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder={`${selectedFilter?.label || "Filter"}...`}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ if (highlightedFilterKey) openFilter(highlightedFilterKey);+ else if (highlightedOptionValue)+ selectOption(highlightedOptionValue);+ }+ }}+ />+ <div className="scrollbar-hide max-h-[50vh] overflow-y-scroll p-2">+ {!selectedFilter ? (+ <div className="flex flex-col gap-1" ref={mainListContainer}>+ {filteredFilters.length ? (+ filteredFilters.map((filter) => (+ <FilterButton+ {...filter}+ key={filter.key}+ highlighted={filter.key === highlightedFilterKey}+ onClick={() => openFilter(filter.key)}+ />+ ))+ ) : (+ <NoMatches />+ )}+ </div>+ ) : (+ <div className="flex flex-col gap-1">+ {selectedFilter.options ? (+ filteredOptions?.length ? (+ filteredOptions?.map((option) => {+ const isSelected =+ activeFilters?.find(+ ({ key }) => key === selectedFilterKey,+ )?.value === option.value;++ return (+ <FilterButton+ {...option}+ key={option.value}+ right={+ isSelected ? (+ <Check className="h-4 w-4" />+ ) : (+ option.right+ )+ }+ highlighted={+ option.value === highlightedOptionValue+ }+ onClick={() => selectOption(option.value)}+ />+ );+ })+ ) : (+ <NoMatches />+ )+ ) : (+ <div+ className="flex items-center justify-center px-2 py-4"+ style={mainListDimensions.current}+ >+ <LoadingSpinner />+ </div>+ )}+ </div>+ )}+ </div>+ </div>+ </AnimatedSizeContainer>+ }+ >+ <button+ type="button"+ className={cn(+ "group flex h-10 cursor-pointer appearance-none items-center gap-x-2 truncate rounded-md border px-3 outline-none transition-all sm:text-sm",+ "border-gray-200 bg-white text-gray-900 placeholder-gray-400 transition-all",+ "disabled:pointer-events-none disabled:bg-gray-100 disabled:text-gray-400",+ "data-[state=open]:border-gray-500 data-[state=open]:ring-4 data-[state=open]:ring-gray-200",+ className,+ )}+ >+ <ListFilter className="h-4 w-4 shrink-0" />+ <span className="flex-1 overflow-hidden text-ellipsis whitespace-nowrap text-left text-gray-900">+ {children ?? "Filter"}+ </span>+ <div className="ml-1">+ {activeFilters?.length ? (+ <div className="flex h-4 w-4 items-center justify-center rounded-full bg-black text-[0.625rem] text-white">+ {activeFilters.length}+ </div>+ ) : (+ <ChevronDown+ className={`h-4 w-4 flex-shrink-0 text-gray-400 transition-transform duration-75 group-data-[state=open]:rotate-180`}+ />+ )}+ </div>+ </button>+ </Popover>+ );+}++function FilterButton({+ icon: Icon,+ label,+ right,+ highlighted,+ onClick,+ ...rest+}: (Filter | FilterOption) & {+ right?: ReactNode;+ highlighted?: boolean;+ onClick: () => void;+}) {+ return (+ <button+ type="button"+ className={cn(+ "flex items-center gap-4 whitespace-nowrap rounded-md px-3 py-2.5 text-left text-sm hover:bg-gray-100 active:bg-gray-200",+ highlighted && "bg-gray-100",+ )}+ onClick={onClick}+ >+ <span className="shrink-0 text-gray-600">+ {isReactNode(Icon) ? Icon : <Icon className="h-4 w-4" />}+ </span>+ {label}+ <div className="ml-1 flex shrink-0 grow justify-end text-gray-500">+ {right}+ </div>+ </button>+ );+}++const NoMatches = () => (+ <p className="my-1 text-center text-sm text-gray-400">No matches</p>+);++const isReactNode = (element: any): element is ReactNode =>+ isValidElement(element);++const Filter = { Select };++export { Filter };diff --git a/packages/ui/src/index.tsx b/packages/ui/src/index.tsxindex 3338237b67..50d0cf21ee 100644--- a/packages/ui/src/index.tsx+++ b/packages/ui/src/index.tsx@@ -9,6 +9,7 @@ export * from "./button";export * from "./checkbox";export * from "./date-picker";export * from "./file-upload";+export * from "./filter";export * from "./form";export * from "./input-select";export * from "./label";diff --git a/packages/ui/src/popover.tsx b/packages/ui/src/popover.tsxindex 9c6f45185e..d97a848340 100644--- a/packages/ui/src/popover.tsx+++ b/packages/ui/src/popover.tsx@@ -13,6 +13,7 @@ export type PopoverProps = PropsWithChildren<{setOpenPopover: (open: boolean) => void;mobileOnly?: boolean;popoverContentClassName?: string;+ onEscapeKeyDown?: (event: KeyboardEvent) => void;}>;export function Popover({@@ -23,6 +24,7 @@ export function Popover({setOpenPopover,mobileOnly,popoverContentClassName,+ onEscapeKeyDown,}: PopoverProps) {const { isMobile } = useMediaQuery();@@ -34,7 +36,10 @@ export function Popover({</Drawer.Trigger><Drawer.Overlay className="fixed inset-0 z-40 bg-gray-100 bg-opacity-10 backdrop-blur" /><Drawer.Portal>- <Drawer.Content className="fixed bottom-0 left-0 right-0 z-50 mt-24 rounded-t-[10px] border-t border-gray-200 bg-white">+ <Drawer.Content+ className="fixed bottom-0 left-0 right-0 z-50 mt-24 rounded-t-[10px] border-t border-gray-200 bg-white"+ onEscapeKeyDown={onEscapeKeyDown}+ ><div className="sticky top-0 z-20 flex w-full items-center justify-center rounded-t-[10px] bg-inherit"><div className="my-3 h-1 w-12 rounded-full bg-gray-300" /></div>@@ -61,6 +66,7 @@ export function Popover({"animate-slide-up-fade z-50 items-center rounded-lg border border-gray-200 bg-white drop-shadow-lg sm:block",popoverContentClassName,)}+ onEscapeKeyDown={onEscapeKeyDown}>{content}</PopoverPrimitive.Content>