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 functionality to filters

Tim Wilsoncb7ba8dba7c5
diff --git a/apps/web/app/api/tags/route.ts b/apps/web/app/api/tags/route.ts
index 782f455e34..08936b02c6 100644
--- a/apps/web/app/api/tags/route.ts
+++ b/apps/web/app/api/tags/route.ts
@@ -14,7 +14,8 @@ import { NextResponse } from "next/server";
export const GET = withWorkspace(
async ({ req, workspace, headers }) => {
const searchParams = getSearchParams(req.url);
- const { search, page, pageSize } = getTagsQuerySchema.parse(searchParams);
+ const { search, ids, page, pageSize } =
+ getTagsQuerySchema.parse(searchParams);
const tags = await prisma.tag.findMany({
where: {
@@ -24,6 +25,11 @@ export const GET = withWorkspace(
contains: search,
},
}),
+ ...(ids && {
+ id: {
+ in: ids,
+ },
+ }),
},
select: {
id: true,
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/page-client.tsx
index a1700955d1..4a6c060bc7 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/page-client.tsx
@@ -60,8 +60,15 @@ function WorkspaceLinks() {
const { slug } = useWorkspace();
- const { filters, activeFilters, onSelect, onRemove, onRemoveAll } =
- useLinkFilters();
+ const {
+ filters,
+ activeFilters,
+ onSelect,
+ onRemove,
+ onRemoveAll,
+ setSearch,
+ setSelectedFilter,
+ } = useLinkFilters();
const { isValidating } = useLinks();
@@ -82,6 +89,8 @@ function WorkspaceLinks() {
activeFilters={activeFilters}
onSelect={onSelect}
onRemove={onRemove}
+ onSearchChange={setSearch}
+ onSelectedFilterChange={setSelectedFilter}
className="w-full"
emptyState={{
tagId: (
diff --git a/apps/web/lib/swr/use-tags.ts b/apps/web/lib/swr/use-tags.ts
index c833ca22de..1e0d0dc24f 100644
--- a/apps/web/lib/swr/use-tags.ts
+++ b/apps/web/lib/swr/use-tags.ts
@@ -9,11 +9,13 @@ const partialQuerySchema = getTagsQuerySchema.partial();
export default function useTags({
query,
-}: { query?: z.infer<typeof partialQuerySchema> } = {}) {
+ enabled = true,
+}: { query?: z.infer<typeof partialQuerySchema>; enabled?: boolean } = {}) {
const { id } = useWorkspace();
const { data: tags, isValidating } = useSWR<TagProps[]>(
id &&
+ enabled &&
`/api/tags?${new URLSearchParams({ workspaceId: id, ...query } as Record<string, any>).toString()}`,
fetcher,
{
diff --git a/apps/web/lib/zod/schemas/tags.ts b/apps/web/lib/zod/schemas/tags.ts
index f75bed045d..15f72cbe33 100644
--- a/apps/web/lib/zod/schemas/tags.ts
+++ b/apps/web/lib/zod/schemas/tags.ts
@@ -10,10 +10,16 @@ export const getTagsQuerySchema = z
.string()
.optional()
.describe("The search term to filter the tags by."),
+ ids: z
+ .union([z.string(), z.array(z.string())])
+ .transform((v) => (Array.isArray(v) ? v : v.split(",")))
+ .optional()
+ .describe("IDs of tags to filter by."),
})
.merge(getPaginationQuerySchema({ pageSize: TAGS_MAX_PAGE_SIZE }));
export const getTagsCountQuerySchema = getTagsQuerySchema.omit({
+ ids: true,
page: true,
pageSize: true,
});
diff --git a/apps/web/ui/analytics/toggle.tsx b/apps/web/ui/analytics/toggle.tsx
index edfd14bad2..9b5c8b203c 100644
--- a/apps/web/ui/analytics/toggle.tsx
+++ b/apps/web/ui/analytics/toggle.tsx
@@ -7,9 +7,13 @@ import {
} from "@/lib/analytics/constants";
import { validDateRangeForPlan } from "@/lib/analytics/utils";
import useDomains from "@/lib/swr/use-domains";
+import useDomainsCount from "@/lib/swr/use-domains-count";
import useTags from "@/lib/swr/use-tags";
+import useTagsCount from "@/lib/swr/use-tags-count";
import useWorkspace from "@/lib/swr/use-workspace";
-import { LinkProps } from "@/lib/types";
+import { LinkProps, TagProps } from "@/lib/types";
+import { DOMAINS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/domains";
+import { TAGS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/tags";
import {
BlurImage,
DateRangePicker,
@@ -62,6 +66,7 @@ import {
useState,
} from "react";
import useSWR from "swr";
+import { useDebounce } from "use-debounce";
import { COLORS_LIST } from "../links/tag-badge";
import AnalyticsOptions from "./analytics-options";
import { AnalyticsContext } from "./analytics-provider";
@@ -94,8 +99,37 @@ export default function Toggle({
const scrolled = useScroll(120);
- const { tags } = useTags();
- const { allDomains: domains, primaryDomain } = useDomains();
+ // Determine whether tags and domains should be fetched async
+ const { data: tagsCount } = useTagsCount();
+ const { data: domainsCount } = useDomainsCount({ includeParams: false });
+ const tagsAsync = Boolean(tagsCount && tagsCount > TAGS_MAX_PAGE_SIZE);
+ const domainsAsync = domainsCount && domainsCount > DOMAINS_MAX_PAGE_SIZE;
+
+ const [selectedFilter, setSelectedFilter] = useState<string | null>(null);
+ const [search, setSearch] = useState("");
+ const [debouncedSearch] = useDebounce(search, 500);
+
+ const { tags, loading: loadingTags } = useTags({
+ query: {
+ search: tagsAsync && selectedFilter === "tagId" ? debouncedSearch : "",
+ },
+ });
+ const {
+ allDomains: domains,
+ primaryDomain,
+ loading: loadingDomains,
+ } = useDomains({
+ includeParams: false,
+ query: {
+ search:
+ domainsAsync && selectedFilter === "domain" ? debouncedSearch : "",
+ },
+ });
+
+ const { tags: selectedTags } = useTags({
+ query: { ids: searchParamsObj.tagId ? [searchParamsObj.tagId] : [] },
+ enabled: tagsAsync,
+ });
const [requestedFilters, setRequestedFilters] = useState<string[]>([]);
@@ -236,6 +270,7 @@ export default function Toggle({
key: "domain",
icon: Globe2,
label: "Domain",
+ shouldFilter: !domainsAsync,
getOptionIcon: (value) => (
<BlurImage
src={`${GOOGLE_FAVICON_URL}${value}`}
@@ -245,10 +280,25 @@ export default function Toggle({
height={16}
/>
),
- options: domains.map((domain) => ({
- value: domain.slug,
- label: domain.slug,
- })),
+ options: loadingDomains
+ ? null
+ : [
+ ...domains.map((domain) => ({
+ value: domain.slug,
+ label: domain.slug,
+ })),
+ // Add currently filtered domain if not already in the list
+ ...(!searchParamsObj.domain ||
+ domains.some((d) => d.slug === searchParamsObj.domain)
+ ? []
+ : [
+ {
+ value: searchParamsObj.domain,
+ label: searchParamsObj.domain,
+ hideDuringSearch: true,
+ },
+ ]),
+ ],
},
{
key: "link",
@@ -296,6 +346,7 @@ export default function Toggle({
key: "tagId",
icon: Tag,
label: "Tag",
+ shouldFilter: !tagsAsync,
getOptionIcon: (value, props) => {
const tagColor =
props.option?.data?.color ??
@@ -312,22 +363,39 @@ export default function Toggle({
) : null;
},
options:
- tags?.map((tag) => ({
- value: tag.id,
- icon: (
- <div
- className={cn(
- "rounded-md p-1.5",
- COLORS_LIST.find(({ color }) => color === tag.color)
- ?.css,
- )}
- >
- <Tag className="h-2.5 w-2.5" />
- </div>
- ),
- label: tag.name,
- data: { color: tag.color },
- })) ?? null,
+ loadingTags ||
+ // Consider tags loading if we can't find the currently filtered tag
+ (searchParamsObj.tagId &&
+ ![...(selectedTags ?? []), ...(tags ?? [])].some(
+ (t) => t.id === searchParamsObj.tagId,
+ ))
+ ? null
+ : [
+ // Add selected tag to list if not already in tags
+ ...(tags ?? []),
+ ...(selectedTags
+ ?.filter((st) => !tags?.some((t) => t.id === st.id))
+ ?.map((st) => ({ ...st, hideDuringSearch: true })) ??
+ []),
+ ].map((tag) => ({
+ value: tag.id,
+ icon: (
+ <div
+ className={cn(
+ "rounded-md p-1.5",
+ COLORS_LIST.find(({ color }) => color === tag.color)
+ ?.css,
+ )}
+ >
+ <Tag className="h-2.5 w-2.5" />
+ </div>
+ ),
+ label: tag.name,
+ data: { color: tag.color },
+ hideDuringSearch: (
+ tag as TagProps & { hideDuringSearch?: boolean }
+ ).hideDuringSearch,
+ })) ?? null,
},
]),
{
@@ -496,6 +564,7 @@ export default function Toggle({
domains,
links,
tags,
+ selectedTags,
countries,
cities,
devices,
@@ -504,6 +573,12 @@ export default function Toggle({
referers,
refererUrls,
urls,
+ tagsAsync,
+ domainsAsync,
+ loadingTags,
+ loadingDomains,
+ searchParamsObj.tagId,
+ searchParamsObj.domain,
],
);
@@ -572,6 +647,8 @@ export default function Toggle({
className="w-full md:w-fit"
filters={filters}
activeFilters={activeFilters}
+ onSearchChange={setSearch}
+ onSelectedFilterChange={setSelectedFilter}
onSelect={async (key, value) => {
if (key === "ai") {
setStreaming(true);
diff --git a/apps/web/ui/links/use-link-filters.tsx b/apps/web/ui/links/use-link-filters.tsx
index e96148b0a2..a920c2d90b 100644
--- a/apps/web/ui/links/use-link-filters.tsx
+++ b/apps/web/ui/links/use-link-filters.tsx
@@ -1,15 +1,25 @@
import useLinksCount from "@/lib/swr/use-links-count";
import useTags from "@/lib/swr/use-tags";
+import useTagsCount from "@/lib/swr/use-tags-count";
import useUsers from "@/lib/swr/use-users";
+import { TagProps } from "@/lib/types";
+import { TAGS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/tags";
import { Avatar, BlurImage, Globe, Tag, User, useRouterStuff } from "@dub/ui";
import { GOOGLE_FAVICON_URL, nFormatter } from "@dub/utils";
-import { useContext, useMemo } from "react";
+import { useContext, useMemo, useState } from "react";
+import { useDebounce } from "use-debounce";
import { LinksDisplayContext } from "./links-display-provider";
import TagBadge from "./tag-badge";
export function useLinkFilters() {
+ const [selectedFilter, setSelectedFilter] = useState<string | null>(null);
+ const [search, setSearch] = useState("");
+ const [debouncedSearch] = useDebounce(search, 500);
+
const domains = useDomainFilterOptions();
- const tags = useTagFilterOptions();
+ const { tags, tagsAsync } = useTagFilterOptions(
+ selectedFilter === "tagIds" ? debouncedSearch : "",
+ );
const users = useUserFilterOptions();
const { queryParams, searchParamsObj } = useRouterStuff();
@@ -40,6 +50,7 @@ export function useLinkFilters() {
icon: Tag,
label: "Tag",
multiple: true,
+ shouldFilter: !tagsAsync,
getOptionIcon: (value, props) => {
const tagColor =
props.option?.data?.color ??
@@ -49,12 +60,13 @@ export function useLinkFilters() {
) : null;
},
options:
- tags?.map(({ id, name, color, count }) => ({
+ tags?.map(({ id, name, color, count, hideDuringSearch }) => ({
value: id,
icon: <TagBadge color={color} withIcon className="sm:p-1" />,
label: name,
data: { color },
right: count,
+ hideDuringSearch,
})) ?? null,
},
{
@@ -137,7 +149,15 @@ export function useLinkFilters() {
});
};
- return { filters, activeFilters, onSelect, onRemove, onRemoveAll };
+ return {
+ filters,
+ activeFilters,
+ onSelect,
+ onRemove,
+ onRemoveAll,
+ setSearch,
+ setSelectedFilter,
+ };
}
function useDomainFilterOptions() {
@@ -165,27 +185,62 @@ function useDomainFilterOptions() {
}, [domainsCount]);
}
-function useTagFilterOptions() {
- const { tags } = useTags();
+function useTagFilterOptions(search: string) {
+ const { searchParamsObj } = useRouterStuff();
+
+ const tagIds = useMemo(
+ () => searchParamsObj.tagIds?.split(",")?.filter(Boolean) ?? [],
+ [searchParamsObj.tagIds],
+ );
+
+ const { data: tagsCount } = useTagsCount();
+ const tagsAsync = Boolean(tagsCount && tagsCount > TAGS_MAX_PAGE_SIZE);
+ const { tags, loading: loadingTags } = useTags({
+ query: { search: tagsAsync ? search : "" },
+ });
+
+ const { tags: selectedTags } = useTags({
+ query: { ids: tagIds },
+ enabled: tagsAsync,
+ });
const { showArchived } = useContext(LinksDisplayContext);
- const { data: tagsCount } = useLinksCount<
+ const { data: tagLinksCount } = useLinksCount<
{
tagId: string;
_count: number;
}[]
>({ groupBy: "tagId", showArchived });
- return useMemo(
- () =>
- tags
- ?.map((tag) => ({
- ...tag,
- count: tagsCount?.find(({ tagId }) => tagId === tag.id)?._count || 0,
- }))
- .sort((a, b) => b.count - a.count) ?? null,
- [tags, tagsCount],
- );
+ const tagsResult = useMemo(() => {
+ return loadingTags ||
+ // Consider tags loading if we can't find the currently filtered tag
+ (tagIds?.length &&
+ tagIds.some(
+ (id) =>
+ ![...(selectedTags ?? []), ...(tags ?? [])].some(
+ (t) => t.id === id,
+ ),
+ ))
+ ? null
+ : (
+ [
+ ...(tags ?? []),
+ // Add selected tag to list if not already in tags
+ ...(selectedTags
+ ?.filter((st) => !tags?.some((t) => t.id === st.id))
+ ?.map((st) => ({ ...st, hideDuringSearch: true })) ?? []),
+ ] as (TagProps & { hideDuringSearch?: boolean })[]
+ )
+ ?.map((tag) => ({
+ ...tag,
+ count:
+ tagLinksCount?.find(({ tagId }) => tagId === tag.id)?._count || 0,
+ }))
+ .sort((a, b) => b.count - a.count) ?? null;
+ }, [loadingTags, tags, selectedTags, tagLinksCount, tagIds]);
+
+ return { tags: tagsResult, tagsAsync };
}
function useUserFilterOptions() {
diff --git a/packages/ui/src/filter/filter-select.tsx b/packages/ui/src/filter/filter-select.tsx
index 30055f6c71..b2cdda32a5 100644
--- a/packages/ui/src/filter/filter-select.tsx
+++ b/packages/ui/src/filter/filter-select.tsx
@@ -25,6 +25,8 @@ type FilterSelectProps = {
onSelect: (key: string, 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"];
@@ -40,6 +42,8 @@ export function FilterSelect({
onSelect,
onRemove,
onOpenFilter,
+ onSearchChange,
+ onSelectedFilterChange,
activeFilters,
askAI,
children,
@@ -49,8 +53,8 @@ export function FilterSelect({
const { isMobile } = useMediaQuery();
// Track main list container/dimensions to maintain size for loading spinner
- const mainListContainer = useRef<HTMLDivElement>(null);
- const mainListDimensions = useRef<{
+ const listContainer = useRef<HTMLDivElement>(null);
+ const listDimensions = useRef<{
width: number;
height: number;
}>();
@@ -82,10 +86,11 @@ export function FilterSelect({
: null;
const openFilter = useCallback((key: Filter["key"]) => {
- if (mainListContainer.current) {
- mainListDimensions.current = {
- width: mainListContainer.current.scrollWidth,
- height: mainListContainer.current.scrollHeight,
+ // Maintain dimensions for loading options
+ if (listContainer.current) {
+ listDimensions.current = {
+ width: listContainer.current.clientWidth,
+ height: listContainer.current.clientHeight,
};
}
@@ -128,6 +133,24 @@ export function FilterSelect({
[activeFilters, selectedFilter, askAI],
);
+ useEffect(() => {
+ onSearchChange?.(search);
+ }, [search]);
+
+ useEffect(() => {
+ onSelectedFilterChange?.(selectedFilterKey);
+ }, [selectedFilterKey]);
+
+ // If filter is selected and has options, maintain dimensions (for async fetches)
+ useEffect(() => {
+ if (selectedFilter?.options && listContainer.current) {
+ listDimensions.current = {
+ width: listContainer.current.clientWidth,
+ height: listContainer.current.clientHeight,
+ };
+ }
+ }, [selectedFilter?.options]);
+
return (
<Popover
openPopover={isOpen}
@@ -145,7 +168,12 @@ export function FilterSelect({
className="rounded-[inherit]"
style={{ transform: "translateZ(0)" }} // Fixes overflow on some browsers
>
- <Command loop>
+ <Command
+ loop
+ shouldFilter={
+ !selectedFilter || selectedFilter.shouldFilter !== false
+ }
+ >
<div className="flex items-center overflow-hidden rounded-t-lg border-b border-gray-200">
<CommandInput
placeholder={`${selectedFilter?.label || "Filter"}...`}
@@ -182,7 +210,7 @@ export function FilterSelect({
</kbd>
)}
</div>
- <FilterScroll key={selectedFilterKey} ref={mainListContainer}>
+ <FilterScroll key={selectedFilterKey} ref={listContainer}>
<Command.List
className={cn(
"flex w-full flex-col gap-1 p-1",
@@ -203,30 +231,32 @@ export function FilterSelect({
</Fragment>
))
: // Filter options
- selectedFilter.options?.map((option) => {
- const isSelected = isOptionSelected(option.value);
-
- return (
- <FilterButton
- key={option.value}
- filter={selectedFilter}
- option={option}
- right={
- isSelected ? (
- <Check className="h-4 w-4" />
- ) : (
- option.right
- )
- }
- onSelect={() => selectOption(option.value)}
- />
- );
- }) ?? (
+ selectedFilter.options
+ ?.filter((option) => !search || !option.hideDuringSearch)
+ ?.map((option) => {
+ const isSelected = isOptionSelected(option.value);
+
+ return (
+ <FilterButton
+ key={option.value}
+ filter={selectedFilter}
+ option={option}
+ right={
+ isSelected ? (
+ <Check className="h-4 w-4" />
+ ) : (
+ option.right
+ )
+ }
+ onSelect={() => selectOption(option.value)}
+ />
+ );
+ }) ?? (
// Filter options loading state
<Command.Loading>
<div
className="-m-1 flex items-center justify-center"
- style={mainListDimensions.current}
+ style={listDimensions.current}
>
<LoadingSpinner />
</div>
diff --git a/packages/ui/src/filter/types.ts b/packages/ui/src/filter/types.ts
index a464fe9f57..ffc0f48d8d 100644
--- a/packages/ui/src/filter/types.ts
+++ b/packages/ui/src/filter/types.ts
@@ -10,6 +10,7 @@ export type Filter = {
key: string;
icon: FilterIcon;
label: string;
+ shouldFilter?: boolean;
separatorAfter?: boolean;
options: FilterOption[] | null;
multiple?: boolean;
@@ -28,5 +29,6 @@ export type FilterOption = {
label: string;
right?: ReactNode;
icon?: FilterIcon;
+ hideDuringSearch?: boolean;
data?: Record<string, any>;
};