The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
multi-select ui filter for link analytics
Pedro Ladeirafd64edb2dc2b
diff --git a/apps/web/lib/stripe/index.ts b/apps/web/lib/stripe/index.tsindex 9e01e9a52a..6b756e8ffc 100644--- a/apps/web/lib/stripe/index.ts+++ b/apps/web/lib/stripe/index.ts@@ -1,13 +1,15 @@import Stripe from "stripe";import { StripeMode } from "../types";-export const stripe = new Stripe(`${process.env.STRIPE_SECRET_KEY}`, {- apiVersion: "2025-05-28.basil",- appInfo: {- name: "Dub.co",- version: "0.1.0",- },-});+export const stripe = process.env.STRIPE_SECRET_KEY+ ? new Stripe(process.env.STRIPE_SECRET_KEY, {+ apiVersion: "2025-05-28.basil",+ appInfo: {+ name: "Dub.co",+ version: "0.1.0",+ },+ })+ : null;const secretMap: Record<StripeMode, string | undefined> = {live: process.env.STRIPE_APP_SECRET_KEY,diff --git a/apps/web/ui/analytics/toggle.tsx b/apps/web/ui/analytics/toggle.tsxindex dbbefa0599..d42aa2d8b3 100644--- a/apps/web/ui/analytics/toggle.tsx+++ b/apps/web/ui/analytics/toggle.tsx@@ -67,8 +67,10 @@ export function AnalyticsToggle({activeFilters,onSelect,onRemove,+ onRemoveFilter,onRemoveAll,onOpenFilter,+ onToggleOperator,streaming,activeFiltersWithStreaming,} = useAnalyticsFilters({ partnerPage, dashboardProps });@@ -81,6 +83,7 @@ export function AnalyticsToggle({onSelect={onSelect}onRemove={onRemove}onOpenFilter={onOpenFilter}+ multiSelect={true}askAI/>);@@ -288,7 +291,9 @@ export function AnalyticsToggle({activeFilters={activeFiltersWithStreaming}onSelect={onSelect}onRemove={onRemove}+ onRemoveFilter={onRemoveFilter}onRemoveAll={onRemoveAll}+ onToggleOperator={onToggleOperator}/><divclassName={cn(diff --git a/apps/web/ui/analytics/use-analytics-filters.tsx b/apps/web/ui/analytics/use-analytics-filters.tsxindex 90760e0ffb..2d509eed2e 100644--- a/apps/web/ui/analytics/use-analytics-filters.tsx+++ b/apps/web/ui/analytics/use-analytics-filters.tsx@@ -8,11 +8,13 @@ import { readStreamableValue } from "@ai-sdk/rsc";import {BlurImage,Filter,+ FilterOperator,LinkLogo,Sliders,useRouterStuff,UTM_PARAMETERS,} from "@dub/ui";+import {Calendar6,Cube,@@ -120,38 +122,63 @@ export function useAnalyticsFilters({const [requestedFilters, setRequestedFilters] = useState<string[]>([]);+ const parseFilterParam = useCallback((value: string): {+ operator: FilterOperator;+ values: string[];+ } => {+ const isNegated = value.startsWith('-');+ const cleanValue = isNegated ? value.slice(1) : value;+ const values = cleanValue.split(',').filter(Boolean);++ const operator: FilterOperator = isNegated+ ? (values.length > 1 ? 'IS_NOT_ONE_OF' : 'IS_NOT')+ : (values.length > 1 ? 'IS_ONE_OF' : 'IS');++ return {+ operator,+ values,+ };+ }, []);+const activeFilters = useMemo(() => {const { domain, key, root, folderId, ...params } = searchParamsObj;// Handle special cases firstconst filters = [// Handle domain/key special case- ...(domain && !key ? [{ key: "domain", value: domain }] : []),+ ...(domain && !key ? [{ key: "domain", operator: "IS" as const, values: [domain] }] : []),...(domain && key? [{key: "link",- value: linkConstructor({ domain, key, pretty: true }),+ operator: "IS" as const,+ values: [linkConstructor({ domain, key, pretty: true })],},]: []),// Handle tagIds special case...(selectedTagIds.length > 0- ? [{ key: "tagIds", value: selectedTagIds }]+ ? [{+ key: "tagIds",+ operator: (selectedTagIds.length > 1 ? "IS_ONE_OF" : "IS") as FilterOperator,+ values: selectedTagIds+ }]: []),// Handle root special case - convert string to boolean- ...(root ? [{ key: "root", value: root === "true" }] : []),+ ...(root ? [{ key: "root", operator: "IS" as const, values: [root === "true"] }] : []),// Handle folderId special case- ...(folderId ? [{ key: "folderId", value: folderId }] : []),+ ...(folderId ? [{ key: "folderId", operator: "IS" as const, values: [folderId] }] : []),// Handle customerId special case...(selectedCustomer? [{key: "customerId",- value:+ operator: "IS" as const,+ values: [selectedCustomer.email ||selectedCustomer["name"] ||selectedCustomer["externalId"],+ ],},]: []),@@ -171,7 +198,8 @@ export function useAnalyticsFilters({const value = params[filter];if (value) {- filters.push({ key: filter, value });+ const { operator, values } = parseFilterParam(value);+ filters.push({ key: filter, operator, values });}});@@ -182,6 +210,7 @@ export function useAnalyticsFilters({partnerPage,selectedCustomerId,selectedCustomer,+ parseFilterParam,]);const isRequested = useCallback(@@ -348,6 +377,7 @@ export function useAnalyticsFilters({key: "link",icon: Hyperlink,label: "Link",+ singleSelect: true,getOptionIcon: (value, props) => {const url = props.option?.data?.url;const [domain, key] = value.split("/");@@ -373,6 +403,7 @@ export function useAnalyticsFilters({key: "domain",icon: Globe2,label: "Domain",+ singleSelect: true,getOptionIcon: (value) => (<BlurImagesrc={`${GOOGLE_FAVICON_URL}${value}`}@@ -394,6 +425,7 @@ export function useAnalyticsFilters({key: "saleType",icon: Receipt2,label: "Sale type",+ singleSelect: true,separatorAfter: true,options: [{@@ -415,6 +447,7 @@ export function useAnalyticsFilters({key: "ai",icon: Magic,label: "Ask AI",+ singleSelect: true,separatorAfter: true,options:aiFilterSuggestions?.map(({ icon, value }) => ({@@ -475,6 +508,7 @@ export function useAnalyticsFilters({key: "folderId",icon: Folder,label: "Folder",+ singleSelect: true,getOptionIcon: (_value, props) => {const folder = props.option?.data?.folder;return folder ? (@@ -528,6 +562,7 @@ export function useAnalyticsFilters({key: "root",icon: Sliders,label: "Link type",+ singleSelect: true,options: [{value: true,@@ -547,14 +582,21 @@ export function useAnalyticsFilters({key: "country",icon: FlagWavy,label: "Country",- getOptionIcon: (value) => (- <img- alt={value}- src={`https://hatscripts.github.io/circle-flags/flags/${value.toLowerCase()}.svg`}- className="size-4 shrink-0"- />- ),- getOptionLabel: (value) => COUNTRIES[value],+ getOptionIcon: (value) => {+ if (typeof value !== 'string') return null;++ return (+ <img+ alt={value}+ src={`https://hatscripts.github.io/circle-flags/flags/${value.toLowerCase()}.svg`}+ className="size-4 shrink-0"+ />+ );+ },+ getOptionLabel: (value) => {+ if (typeof value !== 'string') return String(value);+ return COUNTRIES[value] || value;+ },options:countries?.map(({ country, ...rest }) => ({value: country,@@ -602,10 +644,14 @@ export function useAnalyticsFilters({key: "continent",icon: MapPosition,label: "Continent",- getOptionIcon: (value) => (- <ContinentIcon display={value} className="size-2.5" />- ),- getOptionLabel: (value) => CONTINENTS[value],+ getOptionIcon: (value) => {+ if (typeof value !== 'string') return null;+ return <ContinentIcon display={value} className="size-2.5" />;+ },+ getOptionLabel: (value) => {+ if (typeof value !== 'string') return String(value);+ return CONTINENTS[value] || value;+ },options:continents?.map(({ continent, ...rest }) => ({value: continent,@@ -617,13 +663,16 @@ export function useAnalyticsFilters({key: "device",icon: MobilePhone,label: "Device",- getOptionIcon: (value) => (- <DeviceIcon- display={capitalize(value) ?? value}- tab="devices"- className="h-4 w-4"- />- ),+ getOptionIcon: (value) => {+ if (typeof value !== 'string') return null;+ return (+ <DeviceIcon+ display={capitalize(value) ?? value}+ tab="devices"+ className="h-4 w-4"+ />+ );+ },options:devices?.map(({ device, ...rest }) => ({value: device,@@ -635,9 +684,10 @@ export function useAnalyticsFilters({key: "browser",icon: Window,label: "Browser",- getOptionIcon: (value) => (- <DeviceIcon display={value} tab="browsers" className="h-4 w-4" />- ),+ getOptionIcon: (value) => {+ if (typeof value !== 'string') return null;+ return <DeviceIcon display={value} tab="browsers" className="h-4 w-4" />;+ },options:browsers?.map(({ browser, ...rest }) => ({value: browser,@@ -649,9 +699,10 @@ export function useAnalyticsFilters({key: "os",icon: Cube,label: "OS",- getOptionIcon: (value) => (- <DeviceIcon display={value} tab="os" className="h-4 w-4" />- ),+ getOptionIcon: (value) => {+ if (typeof value !== 'string') return null;+ return <DeviceIcon display={value} tab="os" className="h-4 w-4" />;+ },options:os?.map(({ os, ...rest }) => ({value: os,@@ -683,9 +734,10 @@ export function useAnalyticsFilters({key: "referer",icon: ReferredVia,label: "Referer",- getOptionIcon: (value, props) => (- <ReferrerIcon display={value} className="h-4 w-4" />- ),+ getOptionIcon: (value, props) => {+ if (typeof value !== 'string') return null;+ return <ReferrerIcon display={value} className="h-4 w-4" />;+ },options:referers?.map(({ referer, ...rest }) => ({value: referer,@@ -700,9 +752,10 @@ export function useAnalyticsFilters({key: "refererUrl",icon: ReferredVia,label: "Referrer URL",- getOptionIcon: (value, props) => (- <ReferrerIcon display={value} className="h-4 w-4" />- ),+ getOptionIcon: (value, props) => {+ if (typeof value !== 'string') return null;+ return <ReferrerIcon display={value} className="h-4 w-4" />;+ },options:refererUrls?.map(({ refererUrl, ...rest }) => ({value: refererUrl,@@ -732,9 +785,10 @@ export function useAnalyticsFilters({key,icon: Icon,label: `UTM ${label}`,- getOptionIcon: (value) => (- <Icon display={value} className="h-4 w-4" />- ),+ getOptionIcon: (value) => {+ if (typeof value !== 'string') return null;+ return <Icon display={value} className="h-4 w-4" />;+ },options:utmData[key]?.map((dt) => ({value: dt[key],@@ -749,6 +803,7 @@ export function useAnalyticsFilters({key: "customerId",icon: User,label: "Customer",+ singleSelect: true,hideInFilterDropdown: true,getOptionIcon: () => {return selectedCustomer ? (@@ -775,6 +830,7 @@ export function useAnalyticsFilters({key: "partnerId",icon: Users6,label: "Partner",+ singleSelect: true,hideInFilterDropdown: true,getOptionIcon: () => {return selectedPartner ? (@@ -822,6 +878,27 @@ export function useAnalyticsFilters({const onSelect = useCallback(async (key, value) => {+ if (Array.isArray(value)) {+ if (value.length === 0) {+ queryParams({ del: key, scroll: false });+ } else {+ const currentParam = searchParamsObj[key];+ const isNegated = currentParam?.startsWith("-") ?? false;++ const newParam = isNegated+ ? `-${value.join(",")}`+ : value.join(",");++ queryParams({+ set: { [key]: newParam },+ del: "page",+ scroll: false,+ });+ }++ return;+ }+if (key === "ai") {setStreaming(true);const prompt = value.replace("Ask AI ", "");@@ -844,46 +921,94 @@ export function useAnalyticsFilters({filters: activeFilters,});setStreaming(false);- } else {+ } else if (key === "link") {queryParams({- set:- key === "link"- ? {- domain: new URL(`https://${value}`).hostname,- key: new URL(`https://${value}`).pathname.slice(1) || "_root",- }- : key === "tagIds"- ? {- tagIds: selectedTagIds.concat(value).join(","),- }- : {- [key]: value,- },+ set: {+ domain: new URL(`https://${value}`).hostname,+ key: new URL(`https://${value}`).pathname.slice(1) || "_root",+ },+ del: "page",+ scroll: false,+ });+ } else if (key === "tagIds") {+ queryParams({+ set: {+ tagIds: selectedTagIds.concat(value).join(","),+ },del: "page",scroll: false,});+ } else {+ const currentParam = searchParamsObj[key];++ if (!currentParam) {+ queryParams({+ set: { [key]: value },+ del: "page",+ scroll: false,+ });+ } else {+ const parsed = parseFilterParam(currentParam);++ if (!parsed.values.includes(value)) {+ const newValues = [...parsed.values, value];+ const newParam = parsed.operator.includes("NOT")+ ? `-${newValues.join(",")}`+ : newValues.join(",");++ queryParams({+ set: { [key]: newParam },+ del: "page",+ scroll: false,+ });+ }+ }}},- [queryParams, activeFilters, selectedTagIds],+ [queryParams, activeFilters, selectedTagIds, searchParamsObj, parseFilterParam],);const onRemove = useCallback(- (key, value) =>- queryParams(- key === "tagIds" &&- !(selectedTagIds.length === 1 && selectedTagIds[0] === value)- ? {- set: {- tagIds: selectedTagIds.filter((id) => id !== value).join(","),- },- scroll: false,- }- : {- del: key === "link" ? ["domain", "key", "url"] : key,- scroll: false,+ (key, value) => {+ if (key === "tagIds") {+ if (selectedTagIds.length === 1 && selectedTagIds[0] === value) {+ queryParams({ del: "tagIds", scroll: false });+ } else {+ queryParams({+ set: {+ tagIds: selectedTagIds.filter((id) => id !== value).join(","),},- ),- [queryParams, selectedTagIds],+ scroll: false,+ });+ }+ } else if (key === "link") {+ queryParams({+ del: ["domain", "key", "url"],+ scroll: false,+ });+ } else {+ const currentParam = searchParamsObj[key];++ if (!currentParam) return;++ const parsed = parseFilterParam(currentParam);+ const newValues = parsed.values.filter((v) => v !== value);++ if (newValues.length === 0) {+ queryParams({ del: key, scroll: false });+ } else {+ const newParam = parsed.operator.includes("NOT")+ ? `-${newValues.join(",")}`+ : newValues.join(",");++ queryParams({+ set: { [key]: newParam },+ scroll: false,+ });+ }+ }+ },+ [queryParams, selectedTagIds, searchParamsObj, parseFilterParam],);const onRemoveAll = useCallback(@@ -899,21 +1024,50 @@ export function useAnalyticsFilters({);const onOpenFilter = useCallback(- (key) =>- setRequestedFilters((rf) => (rf.includes(key) ? rf : [...rf, key])),+ (key) => {+ setRequestedFilters((rf) => (rf.includes(key) ? rf : [...rf, key]));+ },[],);+ const onToggleOperator = useCallback(+ (key) => {+ const currentParam = searchParamsObj[key];+ if (!currentParam) return;++ const isNegated = currentParam.startsWith("-");+ const cleanValue = isNegated ? currentParam.slice(1) : currentParam;++ const newParam = isNegated ? cleanValue : `-${cleanValue}`;++ queryParams({+ set: { [key]: newParam },+ scroll: false,+ });+ },+ [searchParamsObj, queryParams],+ );++ const onRemoveFilter = useCallback(+ (key) => {+ queryParams({ del: key, scroll: false });+ },+ [queryParams],+ );+const activeFiltersWithStreaming = useMemo(- () => [- ...activeFilters,- ...(streaming && !activeFilters.length- ? Array.from({ length: 2 }, (_, i) => i).map((i) => ({+ () => {+ return [+ ...activeFilters,+ ...(streaming && !activeFilters.length+ ? Array.from({ length: 2 }, (_, i) => i).map((i) => ({key: "loader",- value: i,+ values: [i],+ operator: "IS" as const,}))- : []),- ],+ : []),+ ];+ },[activeFilters, streaming],);@@ -922,8 +1076,10 @@ export function useAnalyticsFilters({activeFilters,onSelect,onRemove,+ onRemoveFilter,onRemoveAll,onOpenFilter,+ onToggleOperator,streaming,activeFiltersWithStreaming,};diff --git a/package.json b/package.jsonindex be78aebc28..78b89077fd 100644--- a/package.json+++ b/package.json@@ -32,5 +32,5 @@"resolutions": {"chrono-node": "2.7.5"},- "packageManager": "[email protected]"+ "packageManager": "[email protected]"}diff --git a/packages/ui/src/filter/filter-list.tsx b/packages/ui/src/filter/filter-list.tsxindex 91a3e421df..3f949f353a 100644--- a/packages/ui/src/filter/filter-list.tsx+++ b/packages/ui/src/filter/filter-list.tsx@@ -1,32 +1,71 @@import { cn, truncate } from "@dub/utils";+import { Command } from "cmdk";import { X } from "lucide-react";import { AnimatePresence, motion } from "motion/react";-import Link from "next/link";-import { ReactNode, isValidElement, useState } from "react";+import { ReactNode, isValidElement, useState, useCallback } from "react";import { AnimatedSizeContainer } from "../animated-size-container";import { Combobox, ComboboxOption } from "../combobox";import { useKeyboardShortcut } from "../hooks";-import { Icon } from "../icons";-import { Filter, FilterOption } from "./types";+import { Check, Icon } from "../icons";+import { Popover } from "../popover";+import { Tooltip } from "../tooltip";+import { Filter, FilterOption, ActiveFilter, FilterOperator } from "./types";type FilterListProps = {filters: Filter[];- activeFilters?: {- key: Filter["key"];- value: FilterOption["value"];- }[];+ activeFilters?: ActiveFilter[];onRemove: (key: string, value: FilterOption["value"]) => void;+ onRemoveFilter?: (key: string) => void;onRemoveAll: () => void;- onSelect?: (key: string, value: FilterOption["value"]) => void;+ onSelect?: (key: string, value: FilterOption["value"] | FilterOption["value"][]) => void;+ onToggleOperator?: (key: string) => void;className?: string;};+function getOperatorLabel(operator: FilterOperator): string {+ switch (operator) {+ case "IS":+ case "IS_ONE_OF":+ return "is";++ case "IS_NOT":+ case "IS_NOT_ONE_OF":+ return "is not";++ default:+ return "is";+ }+}++function pluralize(word: string, count: number): string {+ if (count === 1) return word.toLowerCase();++ const irregularPlurals: Record<string, string> = {+ 'country': 'countries',+ 'city': 'cities',+ 'category': 'categories',+ };++ const lowerWord = word.toLowerCase();+ if (irregularPlurals[lowerWord]) {+ return irregularPlurals[lowerWord];+ }++ if (lowerWord.endsWith('y') && !['ay', 'ey', 'iy', 'oy', 'uy'].some(ending => lowerWord.endsWith(ending))) {+ return lowerWord.slice(0, -1) + 'ies';+ }++ return lowerWord + 's';+}+export function FilterList({filters,activeFilters,onRemove,+ onRemoveFilter,onRemoveAll,onSelect,+ onToggleOperator,className,}: FilterListProps) {useKeyboardShortcut("Escape", onRemoveAll, { priority: 1 });@@ -44,11 +83,11 @@ export function FilterList({><div className="flex grow flex-wrap gap-x-4 gap-y-2"><AnimatePresence>- {activeFilters?.map(({ key, value: filterValue }) => {+ {activeFilters?.map(({ key, values, operator }) => {if (key === "loader") {return (<motion.div- key={`loader-${filterValue}`}+ key={`loader-${values?.[0] ?? 0}`}initial={{ opacity: 0, y: 4 }}animate={{ opacity: 1, y: 0 }}className="h-9 w-48 animate-pulse rounded-md border border-neutral-200 bg-white"@@ -64,46 +103,49 @@ export function FilterList({return null;}- return (- filter.multiple && Array.isArray(filterValue)- ? filterValue- : [filterValue]- ).map((value) => {- const option = filter.options?.find((o) =>- typeof o.value === "string" && typeof value === "string"- ? o.value.toLowerCase() === value.toLowerCase()- : o.value === value,- );+ const isSingleValue = values.length === 1;+ const displayValues = values.slice(0, 3);++ const displayLabel = isSingleValue+ ? (() => {+ const value = values[0];+ const option = filter.options?.find((o) =>+ typeof o.value === "string" && typeof value === "string"+ ? o.value.toLowerCase() === value.toLowerCase()+ : o.value === value,+ );+ return option?.label ??+ filter.getOptionLabel?.(value, { key: filter.key, option }) ??+ String(value);+ })()+ : `${values.length} ${pluralize(filter.label, values.length)}`;- const OptionIcon =- option?.icon ??- filter.getOptionIcon?.(value, {- key: filter.key,- option,- }) ??- filter.icon;-- const optionLabel =- option?.label ??- filter.getOptionLabel?.(value, { key: filter.key, option }) ??- value;-- const optionPermalink =- option?.permalink ??- filter.getOptionPermalink?.(value) ??- null;-- const OptionDisplay = ({- className,- }: {- className?: string;- }) => (- <div- className={cn(- "flex items-center gap-2.5 px-3 py-2",- className,- )}- >+ const showMultipleIcons = ["country", "city"].includes(key);++ const OptionDisplay = ({+ className,+ }: {+ className?: string;+ }) => {+ let iconDisplay;++ if (isSingleValue) {+ const value = values[0];+ const option = filter.options?.find((o) =>+ typeof o.value === "string" && typeof value === "string"+ ? o.value.toLowerCase() === value.toLowerCase()+ : o.value === value,+ );++ const OptionIcon =+ option?.icon ??+ filter.getOptionIcon?.(value, {+ key: filter.key,+ option,+ }) ??+ filter.icon;++ iconDisplay = (<span className="shrink-0 text-neutral-600">{isReactNode(OptionIcon) ? (OptionIcon@@ -111,116 +153,88 @@ export function FilterList({<OptionIcon className="h-4 w-4" />)}</span>- {optionPermalink ? (- <Link- href={optionPermalink}- target="_blank"- className="cursor-alias decoration-dotted underline-offset-2 hover:underline"- >- {truncate(optionLabel, 30)}- </Link>- ) : (- truncate(optionLabel, 30)- )}- </div>- );+ );+ } else if (showMultipleIcons) {+ iconDisplay = (+ <div className="flex shrink-0 -space-x-1">+ {displayValues.map((value, idx) => {+ const option = filter.options?.find((o) =>+ typeof o.value === "string" && typeof value === "string"+ ? o.value.toLowerCase() === value.toLowerCase()+ : o.value === value,+ );++ const OptionIcon =+ option?.icon ??+ filter.getOptionIcon?.(value, {+ key: filter.key,+ option,+ }) ??+ filter.icon;- return (- <motion.div- key={`${key}-${value}`}- initial={{ opacity: 0, y: 4 }}- animate={{ opacity: 1, y: 0 }}- className="flex items-center divide-x rounded-md border border-neutral-200 bg-white text-sm text-black"- >- {/* Filter */}- <div className="flex items-center gap-2.5 px-3 py-2">- <span className="shrink-0 text-neutral-600">- {isReactNode(filter.icon) ? (- filter.icon- ) : (- <filter.icon className="h-4 w-4" />- )}- </span>- {filter.label}+ return (+ <span+ key={idx}+ className="inline-flex text-neutral-600"+ style={{ zIndex: displayValues.length - idx }}+ >+ {isReactNode(OptionIcon) ? (+ OptionIcon+ ) : (+ <OptionIcon className="h-4 w-4" />+ )}+ </span>+ );+ })}</div>-- {/* is */}- <div className="px-3 py-2 text-neutral-500">is</div>-- {/* Option */}- <div className="flex items-center">- {!filter.options ? (- <div className="flex items-center gap-2.5 px-3 py-2">- <div className="h-5 w-12 animate-pulse rounded-md bg-neutral-200" />- </div>- ) : // show the filter list item dropdown if there's onSelect configured- // and the filter is not hidden in the main filter dropdown itself- onSelect && !filter.hideInFilterDropdown ? (- (() => {- // Precompute options array once- const options: ComboboxOption[] =- filter.options?.map((opt): ComboboxOption => {- const optionIcon =- opt.icon ??- filter.getOptionIcon?.(opt.value, {- key: filter.key,- option: opt,- }) ??- filter.icon;-- return {- label:- opt.label ??- filter.getOptionLabel?.(opt.value, {- key: filter.key,- option: opt,- }) ??- String(opt.value),- value: String(opt.value),- icon: optionIcon,- };- }) ?? [];-- // Find selected option from precomputed array- const selectedOption = options.find((opt) =>- typeof opt.value === "string" &&- typeof value === "string"- ? opt.value.toLowerCase() ===- String(value).toLowerCase()- : opt.value === String(value),- );-- return (- <FilterCombobox- key={`${key}-${value}`}- filter={filter}- value={value}- filterKey={key}- options={options}- selectedOption={selectedOption}- onRemove={onRemove}- onSelect={onSelect}- OptionDisplay={OptionDisplay}- optionLabel={optionLabel}- />- );- })()+ );+ } else {+ iconDisplay = (+ <span className="shrink-0 text-neutral-600">+ {isReactNode(filter.icon) ? (+ filter.icon) : (- OptionDisplay({})+ <filter.icon className="h-4 w-4" />)}- </div>+ </span>+ );+ }- {/* Remove */}- <button- type="button"- className="h-full rounded-r-md p-2 text-neutral-500 ring-inset ring-neutral-500 hover:bg-neutral-100 hover:text-neutral-800 focus:outline-none focus-visible:ring-1"- onClick={() => onRemove(key, value)}- >- <X className="h-3.5 w-3.5" />- </button>- </motion.div>+ return (+ <div+ className={cn(+ "flex items-center gap-2.5 px-3 py-2",+ className,+ )}+ >+ {values.length > 3 && showMultipleIcons ? (+ <Tooltip content={`Max of 3 icons shown`}>+ {iconDisplay}+ </Tooltip>+ ) : (+ iconDisplay+ )}+ {truncate(displayLabel, 30)}+ </div>);- });+ };++ return (+ <OperatorFilterPill+ key={`${key}-${values.join(',')}`}+ filterKey={key}+ filter={filter}+ values={values}+ operator={operator}+ displayLabel={displayLabel}+ displayValues={displayValues}+ OptionDisplay={OptionDisplay}+ onRemove={onRemove}+ onRemoveFilter={onRemoveFilter}+ onSelect={onSelect}+ onToggleOperator={onToggleOperator}+ />+ );})}</AnimatePresence></div>@@ -337,5 +351,263 @@ function FilterCombobox({);}+function OperatorFilterPill({+ filterKey,+ filter,+ values,+ operator,+ displayLabel,+ displayValues,+ OptionDisplay,+ onRemove,+ onRemoveFilter,+ onSelect,+ onToggleOperator,+}: {+ filterKey: string;+ filter: Filter;+ values: FilterOption["value"][];+ operator: FilterOperator;+ displayLabel: string;+ displayValues: FilterOption["value"][];+ OptionDisplay: ({ className }: { className?: string }) => ReactNode;+ onRemove: (key: string, value: FilterOption["value"]) => void;+ onRemoveFilter?: (key: string) => void;+ onSelect?: (key: string, value: FilterOption["value"] | FilterOption["value"][]) => void;+ onToggleOperator?: (key: string) => void;+}) {+ const [operatorDropdownOpen, setOperatorDropdownOpen] = useState(false);+ const [valueDropdownOpen, setValueDropdownOpen] = useState(false);+ const [search, setSearch] = useState("");+ const [initialSelectedValues, setInitialSelectedValues] = useState<Set<FilterOption["value"]>>(new Set());++ const openValueDropdown = useCallback(() => {+ setInitialSelectedValues(new Set(values));+ setValueDropdownOpen(true);+ }, [values]);++ const toggleValue = useCallback((value: FilterOption["value"]) => {+ const isSelected = values.includes(value);+ if (isSelected) {+ onRemove(filterKey, value);+ } else {+ onSelect?.(filterKey, value);+ }+ }, [filterKey, values, onSelect, onRemove]);++ return (+ <motion.div+ initial={{ opacity: 0, y: 4 }}+ animate={{ opacity: 1, y: 0 }}+ className="flex items-center divide-x rounded-md border border-neutral-200 bg-white text-sm text-black"+ >+ <div className="flex items-center gap-2.5 px-3 py-2">+ <span className="shrink-0 text-neutral-600">+ {isReactNode(filter.icon) ? (+ filter.icon+ ) : (+ <filter.icon className="h-4 w-4" />+ )}+ </span>+ {filter.label}+ </div>++ <Popover+ openPopover={operatorDropdownOpen}+ setOpenPopover={setOperatorDropdownOpen}+ content={+ <div className="w-32 p-1">+ <button+ type="button"+ className={cn(+ "flex w-full items-center rounded-md px-3 py-2 text-left text-sm transition-colors hover:bg-neutral-100",+ !operator.includes("NOT") && "bg-neutral-50"+ )}+ onClick={() => {+ if (operator.includes("NOT")) {+ onToggleOperator?.(filterKey);+ }+ setOperatorDropdownOpen(false);+ }}+ >+ is+ </button>+ <button+ type="button"+ className={cn(+ "flex w-full items-center rounded-md px-3 py-2 text-left text-sm transition-colors hover:bg-neutral-100",+ operator.includes("NOT") && "bg-neutral-50"+ )}+ onClick={() => {+ if (!operator.includes("NOT")) {+ onToggleOperator?.(filterKey);+ }+ setOperatorDropdownOpen(false);+ }}+ >+ is not+ </button>+ </div>+ }+ align="center"+ >+ <button+ type="button"+ className="px-3 py-2 text-neutral-500 transition-colors hover:bg-neutral-50 hover:text-neutral-700"+ >+ {getOperatorLabel(operator)}+ </button>+ </Popover>++ <Popover+ openPopover={valueDropdownOpen}+ setOpenPopover={(open) => {+ setValueDropdownOpen(open);+ if (!open) {+ setSearch("");+ setInitialSelectedValues(new Set());+ }+ }}+ content={+ <div onClick={(e) => e.stopPropagation()}>+ <AnimatedSizeContainer+ width+ height+ className="rounded-[inherit]"+ >+ <Command loop shouldFilter={false}>+ <div className="flex items-center overflow-hidden rounded-t-lg border-b border-neutral-200">+ <Command.Input+ placeholder={`${filter.label}...`}+ value={search}+ onValueChange={setSearch}+ className="grow border-0 py-3 pl-4 pr-2 outline-none placeholder:text-neutral-400 focus:ring-0 sm:text-sm"+ autoCapitalize="none"+ />+ </div>+ <div className="scrollbar-hide max-h-[50vh] w-screen overflow-y-scroll sm:w-auto">+ <Command.List className="flex w-full flex-col gap-1 p-1 min-w-[180px]">+ {(() => {+ const filteredOptions = filter.options?.filter(option => {+ if (!search) return true;+ const optionLabel = (+ option.label ??+ filter.getOptionLabel?.(option.value, { key: filter.key, option }) ??+ String(option.value)+ ).toLowerCase();+ return optionLabel.includes(search.toLowerCase());+ }) ?? [];++ const selectedOptions = filteredOptions.filter(option =>+ initialSelectedValues.has(option.value)+ );+ const unselectedOptions = filteredOptions.filter(option =>+ !initialSelectedValues.has(option.value)+ );++ const renderOption = (option: FilterOption) => {+ const isSelected = values.includes(option.value);+ const OptionIcon =+ option.icon ??+ filter.getOptionIcon?.(option.value, {+ key: filter.key,+ option,+ }) ??+ filter.icon;++ const optionLabel =+ option.label ??+ filter.getOptionLabel?.(option.value, { key: filter.key, option }) ??+ String(option.value);++ return (+ <Command.Item+ key={option.value}+ 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-neutral-100",+ )}+ onSelect={() => {+ // Empty onSelect to use pointer events instead+ }}+ onPointerDown={(e) => {+ e.preventDefault();+ }}+ onPointerUp={(e) => {+ e.preventDefault();+ e.stopPropagation();+ toggleValue(option.value);+ }}+ value={optionLabel + option.value}+ >+ <div className={cn(+ "flex h-4 w-4 items-center justify-center rounded border",+ isSelected ? "border-neutral-900 bg-neutral-900" : "border-neutral-300"+ )}>+ {isSelected && <Check className="h-3 w-3 text-white" />}+ </div>+ <span className="shrink-0 text-neutral-600">+ {isReactNode(OptionIcon) ? OptionIcon : <OptionIcon className="h-4 w-4" />}+ </span>+ <span className="flex-1">{truncate(optionLabel, 48)}</span>+ <div className="ml-1 flex shrink-0 justify-end text-neutral-500">+ {option.right}+ </div>+ </Command.Item>+ );+ };++ return (+ <>+ {selectedOptions.map(renderOption)}++ {selectedOptions.length > 0 && unselectedOptions.length > 0 && (+ <Command.Separator className="-mx-1 my-1 border-b border-neutral-200" />+ )}++ {unselectedOptions.map(renderOption)}+ </>+ );+ })()}+ </Command.List>+ </div>+ </Command>+ </AnimatedSizeContainer>+ </div>+ }+ align="start"+ >+ <button+ type="button"+ className="flex items-center transition-colors hover:bg-neutral-50"+ onClick={openValueDropdown}+ >+ {!filter.options ? (+ <div className="flex items-center gap-2.5 px-3 py-2">+ <div className="h-5 w-12 animate-pulse rounded-md bg-neutral-200" />+ </div>+ ) : (+ OptionDisplay({ className: "cursor-pointer" })+ )}+ </button>+ </Popover>++ <button+ type="button"+ className="h-full rounded-r-md p-2 text-neutral-500 ring-inset ring-neutral-500 hover:bg-neutral-100 hover:text-neutral-800 focus:outline-none focus-visible:ring-1"+ onClick={() => {+ if (onRemoveFilter) {+ onRemoveFilter(filterKey);+ } else {+ values.forEach(value => onRemove(filterKey, value));+ }+ }}+ >+ <X className="h-3.5 w-3.5" />+ </button>+ </motion.div>+ );+}+const isReactNode = (element: any): element is ReactNode =>isValidElement(element);diff --git a/packages/ui/src/filter/filter-select.tsx b/packages/ui/src/filter/filter-select.tsxindex 9837cf26e0..70f957d652 100644--- a/packages/ui/src/filter/filter-select.tsx+++ b/packages/ui/src/filter/filter-select.tsx@@ -18,19 +18,17 @@ import { useKeyboardShortcut, useMediaQuery } from "../hooks";import { useScrollProgress } from "../hooks/use-scroll-progress";import { Check, LoadingSpinner, Magic } from "../icons";import { Popover } from "../popover";-import { Filter, FilterOption } from "./types";+import { Filter, FilterOption, ActiveFilter } from "./types";type FilterSelectProps = {filters: Filter[];- onSelect: (key: string, value: FilterOption["value"]) => void;+ onSelect: (key: string, value: FilterOption["value"] | FilterOption["value"][]) => void;onRemove: (key: string, value: FilterOption["value"]) => void;onOpenFilter?: (key: string) => void;onSearchChange?: (search: string) => void;onSelectedFilterChange?: (key: string | null) => void;- activeFilters?: {- key: Filter["key"];- value: FilterOption["value"];- }[];+ activeFilters?: ActiveFilter[];+ multiSelect?: boolean;askAI?: boolean;children?: ReactNode;emptyState?: ReactNode | Record<string, ReactNode>;@@ -45,6 +43,7 @@ export function FilterSelect({onSearchChange,onSelectedFilterChange,activeFilters,+ multiSelect = false,askAI,children,emptyState,@@ -96,8 +95,9 @@ export function FilterSelect({setSearch("");setSelectedFilterKey(key);+onOpenFilter?.(key);- }, []);+ }, [onOpenFilter]);const isOptionSelected = useCallback((value: FilterOption["value"]) => {@@ -107,32 +107,36 @@ export function FilterSelect({({ key }) => key === selectedFilterKey,);- return (- activeFilter?.value === value ||- (activeFilter &&- selectedFilter.multiple &&- Array.isArray(activeFilter.value) &&- activeFilter.value.includes(value))- );+ return activeFilter?.values.includes(value) ?? false;},- [selectedFilter],+ [selectedFilter, activeFilters, selectedFilterKey],);+const selectOption = useCallback((value: FilterOption["value"]) => {if (selectedFilter) {- const isSelected = isOptionSelected(value);-- isSelected- ? onRemove(selectedFilter.key, value)- : onSelect(selectedFilter.key, value);-- if (!selectedFilter.multiple) setIsOpen(false);+ const isSingleSelect = selectedFilter.singleSelect || !multiSelect;+ if (isSingleSelect) {+ const isSelected = isOptionSelected(value);+ isSelected+ ? onRemove(selectedFilter.key, value)+ : onSelect(selectedFilter.key, value);+ setIsOpen(false);+ } else {+ const isSelected = isOptionSelected(value);+ if (isSelected) {+ onRemove(selectedFilter.key, value);+ } else {+ onSelect(selectedFilter.key, value);+ }+ }}},- [activeFilters, selectedFilter, askAI],+ [selectedFilter, multiSelect, isOptionSelected, onSelect, onRemove],);+useEffect(() => {onSearchChange?.(search);}, [search]);@@ -236,6 +240,7 @@ export function FilterSelect({selectedFilter.options?.filter((option) => !search || !option.hideDuringSearch)?.map((option) => {+ const isSingleSelect = selectedFilter.singleSelect || !multiSelect;const isSelected = isOptionSelected(option.value);return (@@ -243,9 +248,15 @@ export function FilterSelect({key={option.value}filter={selectedFilter}option={option}+ showCheckbox={!isSingleSelect}+ isChecked={isSelected}right={- isSelected ? (- <Check className="h-4 w-4" />+ isSingleSelect ? (+ isSelected ? (+ <Check className="h-4 w-4" />+ ) : (+ option.right+ )) : (option.right)@@ -378,11 +389,15 @@ function FilterButton({filter,option,right,+ showCheckbox,+ isChecked,onSelect,}: {filter: Filter;option?: FilterOption;right?: ReactNode;+ showCheckbox?: boolean;+ isChecked?: boolean;onSelect: () => void;}) {const { isMobile } = useMediaQuery();@@ -416,11 +431,19 @@ function FilterButton({onSelect={onSelect}value={label + option?.value}>+ {showCheckbox && (+ <div className={cn(+ "flex h-4 w-4 items-center justify-center rounded border",+ isChecked ? "border-neutral-900 bg-neutral-900" : "border-neutral-300"+ )}>+ {isChecked && <Check className="h-3 w-3 text-white" />}+ </div>+ )}<span className="shrink-0 text-neutral-600">{isReactNode(Icon) ? Icon : <Icon className="h-4 w-4" />}</span>- {truncate(label, 48)}- <div className="ml-1 flex shrink-0 grow justify-end text-neutral-500">+ <span className="flex-1">{truncate(label, 48)}</span>+ <div className="ml-1 flex shrink-0 justify-end text-neutral-500">{right}</div></Command.Item>diff --git a/packages/ui/src/filter/index.ts b/packages/ui/src/filter/index.tsindex d407cd63c9..f4b8512c0e 100644--- a/packages/ui/src/filter/index.ts+++ b/packages/ui/src/filter/index.ts@@ -4,3 +4,4 @@ import { FilterSelect } from "./filter-select";const Filter = { Select: FilterSelect, List: FilterList };export { Filter };+export type { FilterOperator, ActiveFilter, Filter as FilterType, FilterOption } from "./types";diff --git a/packages/ui/src/filter/types.ts b/packages/ui/src/filter/types.tsindex fce15750ba..eaa3623c31 100644--- a/packages/ui/src/filter/types.ts+++ b/packages/ui/src/filter/types.ts@@ -6,6 +6,8 @@ type FilterIcon =| ReactNode| ComponentType<SVGProps<SVGSVGElement>>;+export type FilterOperator = "IS" | "IS_NOT" | "IS_ONE_OF" | "IS_NOT_ONE_OF";+export type Filter = {key: string;icon: FilterIcon;@@ -15,6 +17,7 @@ export type Filter = {shouldFilter?: boolean;separatorAfter?: boolean;multiple?: boolean;+ singleSelect?: boolean; // Force single-select behavior even if multiSelect is enabled globallygetOptionIcon?: (value: FilterOption["value"],props: { key: Filter["key"]; option?: FilterOption },@@ -35,3 +38,9 @@ export type FilterOption = {data?: Record<string, any>;permalink?: string;};++export type ActiveFilter = {+ key: Filter["key"];+ values: FilterOption["value"][];+ operator: FilterOperator;+};