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.

Improve folders linkCount

Steven Teye89d2fcd29d1
diff --git a/apps/web/app/api/folders/route.ts b/apps/web/app/api/folders/route.ts
index a644f4413b..5547b583c8 100644
--- a/apps/web/app/api/folders/route.ts
+++ b/apps/web/app/api/folders/route.ts
@@ -16,7 +16,7 @@ import { NextResponse } from "next/server";
// GET /api/folders - get all folders for a workspace
export const GET = withWorkspace(
async ({ workspace, headers, session, searchParams }) => {
- const { search, includeLinkCount, pageSize, page } =
+ const { search, pageSize, page } =
listFoldersQuerySchema.parse(searchParams);
const folders = await getFolders({
@@ -25,7 +25,6 @@ export const GET = withWorkspace(
search,
pageSize,
page,
- includeLinkCount,
});
return NextResponse.json(FolderSchema.array().parse(folders), {
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/library/folders/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/library/folders/page-client.tsx
index 105ec1180b..9ba4c7f1e1 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/library/folders/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/library/folders/page-client.tsx
@@ -25,11 +25,15 @@ export const FoldersPageClient = () => {
const { AddFolderButton, AddFolderModal } = useAddFolderModal();
- const { data: foldersCount } = useFoldersCount({
- includeParams: true,
- });
const { folders, loading, isValidating } = useFolders({
- includeParams: true,
+ includeParams: ["search", "page"],
+ query: {
+ includeLinkCount: true,
+ },
+ });
+
+ const { data: foldersCount } = useFoldersCount({
+ includeParams: ["search", "page"],
});
const showAllLinkFolder =
diff --git a/apps/web/lib/analytics/get-folder-ids-to-filter.ts b/apps/web/lib/analytics/get-folder-ids-to-filter.ts
index 9462199b4e..3d1d89235c 100644
--- a/apps/web/lib/analytics/get-folder-ids-to-filter.ts
+++ b/apps/web/lib/analytics/get-folder-ids-to-filter.ts
@@ -24,7 +24,7 @@ export const getFolderIdsToFilter = async ({
const folders = await getFolders({
workspaceId: workspace.id,
userId,
- excludeBulkFolders: true,
+ type: "default",
pageSize: 1000, // TODO: might need to handle this if folks have > 1000 folders in the future
});
diff --git a/apps/web/lib/folder/get-folders.ts b/apps/web/lib/folder/get-folders.ts
index 74fcf9b826..9080c3e247 100644
--- a/apps/web/lib/folder/get-folders.ts
+++ b/apps/web/lib/folder/get-folders.ts
@@ -5,20 +5,16 @@ export const getFolders = async ({
workspaceId,
userId,
search,
- includeLinkCount = false,
- excludeBulkFolders = false,
pageSize = FOLDERS_MAX_PAGE_SIZE,
page = 1,
}: {
workspaceId: string;
userId: string;
- includeLinkCount?: boolean;
- excludeBulkFolders?: boolean;
search?: string;
pageSize?: number;
page?: number;
}) => {
- const folders = await prisma.folder.findMany({
+ return await prisma.folder.findMany({
where: {
projectId: workspaceId,
OR: [
@@ -49,11 +45,6 @@ export const getFolders = async ({
contains: search,
},
}),
- ...(excludeBulkFolders && {
- type: {
- not: "mega",
- },
- }),
},
select: {
id: true,
@@ -62,13 +53,6 @@ export const getFolders = async ({
accessLevel: true,
createdAt: true,
updatedAt: true,
- ...(includeLinkCount && {
- _count: {
- select: {
- links: true,
- },
- },
- }),
},
orderBy: {
createdAt: "asc",
@@ -76,11 +60,4 @@ export const getFolders = async ({
take: pageSize,
skip: (page - 1) * pageSize,
});
-
- return folders.map((folder) => ({
- ...folder,
- ...(includeLinkCount && {
- linkCount: folder._count.links,
- }),
- }));
};
diff --git a/apps/web/lib/swr/use-folders-count.ts b/apps/web/lib/swr/use-folders-count.ts
index 6629fc1036..a49e215a20 100644
--- a/apps/web/lib/swr/use-folders-count.ts
+++ b/apps/web/lib/swr/use-folders-count.ts
@@ -4,10 +4,10 @@ import useSWR from "swr";
import useWorkspace from "./use-workspace";
export default function useFoldersCount({
- includeParams = false,
+ includeParams = [],
query,
}: {
- includeParams?: boolean;
+ includeParams?: string[];
query?: Record<string, any>;
} = {}) {
const { id: workspaceId, plan } = useWorkspace();
@@ -16,7 +16,7 @@ export default function useFoldersCount({
const qs = getQueryString(
{ workspaceId, ...query },
- { include: includeParams ? ["search"] : [] },
+ { include: includeParams },
);
const { data, error } = useSWR<number>(
diff --git a/apps/web/lib/swr/use-folders.ts b/apps/web/lib/swr/use-folders.ts
index f8b8fb28a9..21523125b1 100644
--- a/apps/web/lib/swr/use-folders.ts
+++ b/apps/web/lib/swr/use-folders.ts
@@ -5,31 +5,27 @@ import useSWR, { SWRConfiguration } from "swr";
import useWorkspace from "./use-workspace";
export default function useFolders({
- includeParams = false,
- includeLinkCount = false,
+ includeParams = [],
query,
options,
}: {
- includeParams?: boolean;
- includeLinkCount?: boolean;
+ includeParams?: string[];
query?: Record<string, any>;
options?: SWRConfiguration;
} = {}) {
const { id: workspaceId, plan } = useWorkspace();
const { getQueryString } = useRouterStuff();
- const qs = getQueryString(
- { workspaceId, ...query },
- { include: includeParams ? undefined : [] },
- );
-
const {
data: folders,
isValidating,
isLoading,
} = useSWR<Folder[]>(
workspaceId && plan !== "free"
- ? `/api/folders${qs}${includeLinkCount ? "&includeLinkCount=true" : ""}`
+ ? `/api/folders${getQueryString(
+ { workspaceId, ...query },
+ { include: includeParams },
+ )}`
: null,
fetcher,
{
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index a4e900875e..08c5f5264e 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -464,7 +464,7 @@ export type FolderWithPermissions = {
export type FolderSummary = Pick<
Folder,
- "id" | "name" | "accessLevel" | "linkCount"
+ "id" | "name" | "accessLevel" | "type"
>;
// Rewards
diff --git a/apps/web/lib/zod/schemas/folders.ts b/apps/web/lib/zod/schemas/folders.ts
index 545af96d16..8881f42a91 100644
--- a/apps/web/lib/zod/schemas/folders.ts
+++ b/apps/web/lib/zod/schemas/folders.ts
@@ -5,7 +5,7 @@ import {
import { FolderAccessLevel } from "@/lib/types";
import z from "@/lib/zod";
import { FolderType, FolderUserRole } from "@dub/prisma/client";
-import { booleanQuerySchema, getPaginationQuerySchema } from "./misc";
+import { getPaginationQuerySchema } from "./misc";
const workspaceFolderAccess = z
.enum(
@@ -27,10 +27,6 @@ export const FolderSchema = z.object({
name: z.string().describe("The name of the folder."),
type: z.enum(Object.keys(FolderType) as [FolderType, ...FolderType[]]),
accessLevel: workspaceFolderAccess,
- linkCount: z
- .number()
- .describe("The number of links in the folder.")
- .default(0),
createdAt: z.date().describe("The date the folder was created."),
updatedAt: z.date().describe("The date the folder was updated."),
});
@@ -48,9 +44,6 @@ export const listFoldersQuerySchema = z
.string()
.optional()
.describe("The search term to filter the folders by."),
- includeLinkCount: booleanQuerySchema
- .optional()
- .describe("Whether to include the link count in the response."),
})
.merge(getPaginationQuerySchema({ pageSize: FOLDERS_MAX_PAGE_SIZE }));
diff --git a/apps/web/ui/folders/folder-card.tsx b/apps/web/ui/folders/folder-card.tsx
index e735697377..fd8ab26e34 100644
--- a/apps/web/ui/folders/folder-card.tsx
+++ b/apps/web/ui/folders/folder-card.tsx
@@ -7,11 +7,10 @@ import {
import useLinksCount from "@/lib/swr/use-links-count";
import useWorkspace from "@/lib/swr/use-workspace";
import { Folder } from "@/lib/types";
-import { useIntersectionObserver } from "@dub/ui";
import { Globe } from "@dub/ui/icons";
-import { cn, nFormatter } from "@dub/utils";
+import { cn, nFormatter, pluralize } from "@dub/utils";
import Link from "next/link";
-import { useRef } from "react";
+import { useMemo } from "react";
import { FolderActions } from "./folder-actions";
import { FolderIcon } from "./folder-icon";
import { RequestFolderEditAccessButton } from "./request-edit-button";
@@ -74,38 +73,46 @@ export const FolderCard = ({ folder }: { folder: Folder }) => {
)}
</span>
- {folder.type !== "mega" && <LinksCount folderId={folder.id} />}
+ <FolderLinksCount folder={folder} />
</div>
</div>
);
};
-function LinksCount({ folderId }: { folderId: string }) {
- const ref = useRef<HTMLDivElement>(null);
+function FolderLinksCount({ folder }: { folder: Folder }) {
+ const { data: folderLinksCount, loading } = useLinksCount<
+ {
+ folderId: string;
+ _count: number;
+ }[]
+ >({ query: { groupBy: "folderId" } });
- const entry = useIntersectionObserver(ref);
- const isInView = entry?.isIntersecting;
+ const folderLinkCount = useMemo(() => {
+ return (
+ folderLinksCount?.find(
+ ({ folderId }) =>
+ folderId === folder.id ||
+ (folder.id === "unsorted" && folderId === null),
+ )?._count || 0
+ );
+ }, [folderLinksCount, folder.id]);
- const { data: linkCount, loading } = useLinksCount({
- enabled: isInView,
- ignoreParams: true,
- query:
- folderId === "unsorted"
- ? {}
- : {
- folderId,
- },
- });
+ console.log({ folderLinkCount });
return (
- <div ref={ref} className="mt-1.5 flex items-center gap-1 text-neutral-500">
+ <div className="mt-1.5 flex items-center gap-1 text-neutral-500">
<Globe className="size-3.5" />
{loading ? (
<div className="h-5 w-12 animate-pulse rounded-md bg-neutral-200" />
) : (
<span className="text-sm font-normal">
- {nFormatter(linkCount)} link{linkCount !== 1 && "s"}
+ {folder.type === "mega"
+ ? "1,000+ links"
+ : `${nFormatter(folderLinkCount, { full: true })} ${pluralize(
+ "link",
+ folderLinkCount,
+ )}`}
</span>
)}
</div>
diff --git a/apps/web/ui/folders/folder-permissions-panel.tsx b/apps/web/ui/folders/folder-permissions-panel.tsx
index e61fd23173..a4decbe7bf 100644
--- a/apps/web/ui/folders/folder-permissions-panel.tsx
+++ b/apps/web/ui/folders/folder-permissions-panel.tsx
@@ -8,15 +8,16 @@ import {
useCheckFolderPermission,
useFolderPermissions,
} from "@/lib/swr/use-folder-permissions";
+import useLinksCount from "@/lib/swr/use-links-count";
import useWorkspace from "@/lib/swr/use-workspace";
import { Folder, FolderUser } from "@/lib/types";
import { FolderUserRole } from "@dub/prisma/client";
import { Avatar, BlurImage, Button, Tooltip, TooltipContent } from "@dub/ui";
import { Globe, UserCheck } from "@dub/ui/icons";
-import { cn, fetcher, nFormatter, OG_AVATAR_URL } from "@dub/utils";
+import { cn, fetcher, nFormatter, OG_AVATAR_URL, pluralize } from "@dub/utils";
import { useSession } from "next-auth/react";
import { useAction } from "next-safe-action/hooks";
-import { useState } from "react";
+import { useMemo, useState } from "react";
import { toast } from "sonner";
import useSWR, { mutate } from "swr";
import { Drawer } from "vaul";
@@ -31,7 +32,7 @@ import { RequestFolderEditAccessButton } from "./request-edit-button";
interface FolderPermissionsPanelProps {
showPanel: boolean;
setShowPanel: (showPanel: boolean) => void;
- folder: Pick<Folder, "id" | "name" | "accessLevel" | "linkCount">;
+ folder: Pick<Folder, "id" | "name" | "accessLevel">;
onSuccess?: () => void;
}
@@ -68,6 +69,22 @@ const FolderPermissionsPanel = ({
keepPreviousData: true,
},
);
+ const { data: folderLinksCount, loading } = useLinksCount<
+ {
+ folderId: string;
+ _count: number;
+ }[]
+ >({ query: { groupBy: "folderId" } });
+
+ const folderLinkCount = useMemo(() => {
+ return (
+ folderLinksCount?.find(
+ ({ folderId }) =>
+ folderId === folder.id ||
+ (folder.id === "unsorted" && folderId === null),
+ )?._count || 0
+ );
+ }, [folderLinksCount, folder.id]);
const updateWorkspaceAccessLevel = async (accessLevel: string) => {
setIsUpdating(true);
@@ -177,8 +194,8 @@ const FolderPermissionsPanel = ({
<div className="mt-1.5 flex items-center gap-1 text-neutral-500">
<Globe className="size-3.5" />
<span className="text-sm font-normal">
- {nFormatter(folder.linkCount)} link
- {folder.linkCount !== 1 && "s"}
+ {nFormatter(folderLinkCount, { full: true })}{" "}
+ {pluralize("link", folderLinkCount)}
</span>
</div>
</div>
@@ -272,7 +289,7 @@ const FolderUserRow = ({
folder,
}: {
user: FolderUser;
- folder: Pick<Folder, "id" | "name" | "accessLevel" | "linkCount">;
+ folder: Pick<Folder, "id" | "name" | "accessLevel">;
}) => {
const { data: session } = useSession();
const { id: workspaceId } = useWorkspace();
@@ -363,7 +380,7 @@ const FolderUserPlaceholder = () => (
);
export function useFolderPermissionsPanel(
- folder: Pick<Folder, "id" | "name" | "accessLevel" | "linkCount">,
+ folder: Pick<Folder, "id" | "name" | "accessLevel" | "type">,
) {
const [showFolderPermissionsPanel, setShowFolderPermissionsPanel] =
useState(false);
diff --git a/apps/web/ui/links/use-folder-filter-options.ts b/apps/web/ui/links/use-folder-filter-options.ts
new file mode 100644
index 0000000000..f69aaf7b8a
--- /dev/null
+++ b/apps/web/ui/links/use-folder-filter-options.ts
@@ -0,0 +1,42 @@
+import useFolders from "@/lib/swr/use-folders";
+import useFoldersCount from "@/lib/swr/use-folders-count";
+import useLinksCount from "@/lib/swr/use-links-count";
+import { FOLDERS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/folders";
+import { useMemo } from "react";
+
+export function useFolderFilterOptions({ search }: { search: string }) {
+ const { data: foldersCount } = useFoldersCount();
+ const foldersAsync = Boolean(
+ foldersCount && foldersCount > FOLDERS_MAX_PAGE_SIZE,
+ );
+ const { folders, loading: loadingFolders } = useFolders({
+ query: { search: foldersAsync ? search : "" },
+ });
+
+ const { data: folderLinksCount } = useLinksCount<
+ {
+ folderId: string;
+ _count: number;
+ }[]
+ >({ query: { groupBy: "folderId" } });
+
+ const foldersResult = useMemo(() => {
+ return (
+ (loadingFolders ||
+ [...(folders ?? [])]
+ .map((folder) => ({
+ ...folder,
+ count:
+ folderLinksCount?.find(
+ ({ folderId }) =>
+ folderId === folder.id ||
+ (folder.id === "unsorted" && folderId === null),
+ )?._count || 0,
+ }))
+ .sort((a, b) => b.count - a.count)) ??
+ null
+ );
+ }, [loadingFolders, folders, folderLinksCount]);
+
+ return { folders: foldersResult, foldersAsync };
+}