The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
WIP folder sharing
Tim Wilson278a9864141a
diff --git a/apps/web/app/api/dashboards/route.ts b/apps/web/app/api/dashboards/route.tsindex 85c0c9fd52..f9d6ef2d4f 100644--- a/apps/web/app/api/dashboards/route.ts+++ b/apps/web/app/api/dashboards/route.ts@@ -2,8 +2,10 @@ import { createId } from "@/lib/api/create-id";import { getLinkOrThrow } from "@/lib/api/links/get-link-or-throw";import { withWorkspace } from "@/lib/auth";import { verifyFolderAccess } from "@/lib/folder/permissions";-import { dashboardSchema } from "@/lib/zod/schemas/dashboard";-import { domainKeySchema } from "@/lib/zod/schemas/links";+import {+ createDashboardQuerySchema,+ dashboardSchema,+} from "@/lib/zod/schemas/dashboard";import { prisma } from "@dub/prisma";import { waitUntil } from "@vercel/functions";import { NextResponse } from "next/server";@@ -26,41 +28,72 @@ export const GET = withWorkspace(// POST /api/dashboards – create a new dashboardexport const POST = withWorkspace(async ({ searchParams, workspace, session }) => {- const { domain, key } = domainKeySchema.parse(searchParams);+ const params = createDashboardQuerySchema.parse(searchParams);- const link = await getLinkOrThrow({- workspaceId: workspace.id,- domain,- key,- });+ if ("key" in params) {+ const { domain, key } = params;+ const link = await getLinkOrThrow({+ workspaceId: workspace.id,+ domain,+ key,+ });++ if (link.folderId) {+ await verifyFolderAccess({+ workspace,+ userId: session.user.id,+ folderId: link.folderId,+ requiredPermission: "folders.links.write",+ });+ }++ const dashboard = await prisma.dashboard.create({+ data: {+ id: createId({ prefix: "dash_" }),+ linkId: link.id,+ projectId: workspace.id,+ userId: link.userId,+ },+ });++ // for backwards compatibility, we'll update the link to have publicStats = true+ waitUntil(+ prisma.link.update({+ where: { id: link.id },+ data: { publicStats: true },+ }),+ );- if (link.folderId) {- await verifyFolderAccess({+ return NextResponse.json(dashboardSchema.parse(dashboard));+ } else {+ const { folderId } = params;++ const folder = await verifyFolderAccess({workspace,userId: session.user.id,- folderId: link.folderId,+ folderId: folderId,requiredPermission: "folders.links.write",});- }- const dashboard = await prisma.dashboard.create({- data: {- id: createId({ prefix: "dash_" }),- linkId: link.id,- projectId: workspace.id,- userId: link.userId,- },- });+ const dashboard = await prisma.dashboard.create({+ data: {+ id: createId({ prefix: "dash_" }),+ folderId,+ projectId: workspace.id,+ userId: session.user.id,+ },+ });- // for backwards compatibility, we'll update the link to have publicStats = true- waitUntil(- prisma.link.update({- where: { id: link.id },- data: { publicStats: true },- }),- );+ // for backwards compatibility, we'll update the link to have publicStats = true+ waitUntil(+ prisma.link.updateMany({+ where: { folderId },+ data: { publicStats: true },+ }),+ );- return NextResponse.json(dashboardSchema.parse(dashboard));+ return NextResponse.json(dashboardSchema.parse(dashboard));+ }},{requiredPermissions: ["links.write"],diff --git a/apps/web/app/api/folders/[folderId]/dashboard/route.ts b/apps/web/app/api/folders/[folderId]/dashboard/route.tsnew file mode 100644index 0000000000..a57148b367--- /dev/null+++ b/apps/web/app/api/folders/[folderId]/dashboard/route.ts@@ -0,0 +1,32 @@+import { withWorkspace } from "@/lib/auth";+import { verifyFolderAccess } from "@/lib/folder/permissions";+import { dashboardSchema } from "@/lib/zod/schemas/dashboard";+import { prisma } from "@dub/prisma";+import { NextResponse } from "next/server";++// GET /folders/[folderId]/dashboard – get dashboard for a given folder+export const GET = withWorkspace(+ async ({ params, workspace, session }) => {+ const { folderId } = params;++ const folder = await verifyFolderAccess({+ workspace,+ userId: session.user.id,+ folderId,+ requiredPermission: "folders.read",+ });++ const dashboard = await prisma.dashboard.findUnique({+ where: {+ folderId: folder.id,+ },+ });++ if (!dashboard) return NextResponse.json(null);++ return NextResponse.json(dashboardSchema.parse(dashboard));+ },+ {+ requiredPermissions: ["folders.read"],+ },+);diff --git a/apps/web/lib/swr/use-folder-link-count.ts b/apps/web/lib/swr/use-folder-link-count.tsindex b48d27131d..0a105a21eb 100644--- a/apps/web/lib/swr/use-folder-link-count.ts+++ b/apps/web/lib/swr/use-folder-link-count.ts@@ -2,8 +2,15 @@ import { useMemo } from "react";import { FolderLinkCount } from "../types";import useLinksCount from "./use-links-count";-export function useFolderLinkCount({ folderId }: { folderId: string | null }) {+export function useFolderLinkCount({+ folderId,+ enabled = true,+}: {+ folderId: string | null;+ enabled?: boolean;+}) {const { data: folderLinksCount, loading } = useLinksCount<FolderLinkCount[]>({+ enabled,query: {groupBy: "folderId",},diff --git a/apps/web/lib/swr/use-folder.ts b/apps/web/lib/swr/use-folder.tsindex 22eedaeb63..82f73fd1f0 100644--- a/apps/web/lib/swr/use-folder.ts+++ b/apps/web/lib/swr/use-folder.ts@@ -23,6 +23,7 @@ export default function useFolder({data: folder,isValidating,isLoading,+ error,} = useSWR<Folder>(swrEnabled ? `/api/folders/${folderId}?workspaceId=${workspaceId}` : null,fetcher,@@ -36,5 +37,6 @@ export default function useFolder({folder,loading: isLoading,isValidating,+ error,};}diff --git a/apps/web/lib/zod/schemas/dashboard.ts b/apps/web/lib/zod/schemas/dashboard.tsindex 3fc7811c11..635748265c 100644--- a/apps/web/lib/zod/schemas/dashboard.ts+++ b/apps/web/lib/zod/schemas/dashboard.ts@@ -1,8 +1,10 @@import { z } from "zod";+import { domainKeySchema } from "./links";export const dashboardSchema = z.object({id: z.string(),linkId: z.string().nullable(),+ folderId: z.string().nullable(),projectId: z.string().nullable(),userId: z.string().nullable(),password: z.string().nullable(),@@ -11,6 +13,12 @@ export const dashboardSchema = z.object({updatedAt: z.date(),});+export const createDashboardQuerySchema = domainKeySchema.or(+ z.object({+ folderId: z.string(),+ }),+);+export const updateDashboardBodySchema = dashboardSchema.pick({doIndex: true,password: true,diff --git a/apps/web/ui/analytics/analytics-provider.tsx b/apps/web/ui/analytics/analytics-provider.tsxindex 7168cb8814..4c849415d5 100644--- a/apps/web/ui/analytics/analytics-provider.tsx+++ b/apps/web/ui/analytics/analytics-provider.tsx@@ -63,6 +63,7 @@ export const AnalyticsContext = createContext<{domain?: string;key?: string;url?: string;+ folderId?: string;queryString: string;start?: Date;end?: Date;@@ -291,6 +292,7 @@ export default function AnalyticsProvider({domain: domain || undefined, // domain for the link (e.g. dub.sh, stey.me, etc.)key: key ? decodeURIComponent(key) : undefined, // link key (e.g. github, weathergpt, etc.)url: dashboardProps?.url, // url for the link (only for public stats pages)+ folderId: folderId || undefined, // id of the folder to filter bystart, // start of time periodend, // end of time periodinterval, /// time period intervaldiff --git a/apps/web/ui/analytics/share-button.tsx b/apps/web/ui/analytics/share-button.tsxindex b2adfdc3b9..0d5ccdda01 100644--- a/apps/web/ui/analytics/share-button.tsx+++ b/apps/web/ui/analytics/share-button.tsx@@ -4,18 +4,31 @@ import { useShareDashboardModal } from "../modals/share-dashboard-modal";import { AnalyticsContext } from "./analytics-provider";export function ShareButton() {- const { domain, key, partnerPage } = useContext(AnalyticsContext);+ const { domain, key, folderId, partnerPage } = useContext(AnalyticsContext);- return domain && key && !partnerPage ? (+ if (partnerPage) return null;++ return domain && key ? (<ShareButtonInner domain={domain} _key={key} />+ ) : folderId ? (+ <ShareButtonInner folderId={folderId} />) : null;}const ShareButtonInner = memo(- ({ domain, _key }: { domain: string; _key: string }) => {- const { ShareDashboardModal, setShowShareDashboardModal } =- useShareDashboardModal({ domain, _key });+ ({+ domain,+ _key,+ folderId,+ }:+ | { domain: string; _key: string; folderId?: never }+ | { folderId: string; domain?: never; _key?: never }) => {const { isMobile } = useMediaQuery();+ const { ShareDashboardModal, setShowShareDashboardModal } =+ useShareDashboardModal(+ domain && _key ? { domain, _key } : { folderId: folderId! },+ );+return (<><ShareDashboardModal />diff --git a/apps/web/ui/modals/share-dashboard-modal.tsx b/apps/web/ui/modals/share-dashboard-modal.tsxindex 6b6305e1ce..b7b4c3a161 100644--- a/apps/web/ui/modals/share-dashboard-modal.tsx+++ b/apps/web/ui/modals/share-dashboard-modal.tsx@@ -1,5 +1,7 @@+import useFolder from "@/lib/swr/use-folder";+import { useFolderLinkCount } from "@/lib/swr/use-folder-link-count";import useWorkspace from "@/lib/swr/use-workspace";-import { DashboardProps, LinkProps } from "@/lib/types";+import { DashboardProps, Folder, LinkProps } from "@/lib/types";import { updateDashboardBodySchema } from "@/lib/zod/schemas/dashboard";import {AnimatedSizeContainer,@@ -12,13 +14,15 @@ import {Tick,useCopyToClipboard,} from "@dub/ui";-import { ArrowTurnRight2, Globe } from "@dub/ui/icons";+import { ArrowTurnRight2, Folder as FolderIcon, Globe } from "@dub/ui/icons";import {APP_DOMAIN,fetcher,getApexDomain,getPrettyUrl,linkConstructor,+ nFormatter,+ pluralize,} from "@dub/utils";import { useCallback, useEffect, useMemo, useState } from "react";import { useForm } from "react-hook-form";@@ -26,12 +30,22 @@ import { toast } from "sonner";import useSWR from "swr";import { z } from "zod";-interface ShareDashboardModalProps {+type ShareDashboardModalInnerProps =+ | {+ domain: string;+ _key: string;+ folderId?: never;+ }+ | {+ folderId: string;+ domain?: never;+ _key?: never;+ };++type ShareDashboardModalProps = {showModal: boolean;setShowModal: (showModal: boolean) => void;- domain: string;- _key: string;-}+} & ShareDashboardModalInnerProps;function ShareDashboardModal(props: ShareDashboardModalProps) {return (@@ -44,10 +58,13 @@ function ShareDashboardModal(props: ShareDashboardModalProps) {function ShareDashboardModalInner({domain,_key: key,+ folderId,}: ShareDashboardModalProps) {const { id: workspaceId } = useWorkspace();const [isRemoving, setIsRemoving] = useState(false);+ const { folder, error: folderError } = useFolder({ folderId });+const { data: link, error: linkError } = useSWR<LinkProps>(workspaceId && domain && key? `/api/links/info?${new URLSearchParams({ workspaceId, domain, key }).toString()}`@@ -59,9 +76,11 @@ function ShareDashboardModalInner({);const { data: dashboard, mutate } = useSWR<DashboardProps>(- link?.id- ? `/api/links/${link.id}/dashboard?workspaceId=${workspaceId}`- : undefined,+ folder?.id+ ? `/api/folders/${folder.id}/dashboard?workspaceId=${workspaceId}`+ : link?.id+ ? `/api/links/${link.id}/dashboard?workspaceId=${workspaceId}`+ : undefined,fetcher,{dedupingInterval: 60000,@@ -95,7 +114,7 @@ function ShareDashboardModalInner({setIsCreating(true);const res = await fetch(- `/api/dashboards?${new URLSearchParams({ workspaceId, domain, key }).toString()}`,+ `/api/dashboards?${new URLSearchParams({ workspaceId, ...(domain && key ? { domain, key } : { folderId: folderId! }) }).toString()}`,{method: "POST",headers: {@@ -186,7 +205,11 @@ function ShareDashboardModalInner({Share dashboard</h3><div className="bg-neutral-50 px-6 pb-6 pt-4">- <LinkCard link={link} isError={Boolean(linkError)} />+ {folderId ? (+ <FolderCard folder={folder} isError={Boolean(folderError)} />+ ) : (+ <LinkCard link={link} isError={Boolean(linkError)} />+ )}<AnimatedSizeContainerheighttransition={{ duration: 0.2, ease: "easeInOut" }}@@ -363,9 +386,64 @@ function LinkCard({);}-export function useShareDashboardModal(- props: Pick<ShareDashboardModalProps, "domain" | "_key">,-) {+function FolderCard({+ folder,+ isError,+}: {+ folder: Folder | undefined;+ isError: boolean;+}) {+ const { folderLinkCount } = useFolderLinkCount({+ enabled: Boolean(folder?.id) && folder?.type !== "mega",+ folderId: folder?.id ?? null,+ });++ return (+ <div className="flex items-center gap-3 rounded-lg border border-neutral-300 bg-white p-3">+ {isError ? (+ <span className="text-sm text-neutral-400">Failed to load folder</span>+ ) : folder === undefined ? (+ <>+ <div className="m-px size-9 animate-pulse rounded-full bg-neutral-200" />+ <div className="flex flex-col gap-2">+ <div className="h-5 w-24 max-w-full animate-pulse rounded-md bg-neutral-200" />+ <div className="h-4 w-32 max-w-full animate-pulse rounded-md bg-neutral-200" />+ </div>+ </>+ ) : (+ <>+ <div className="relative flex shrink-0 items-center justify-center rounded-full border border-blue-200">+ {/* Background gradient + white border */}+ <div className="absolute inset-0 rounded-full border border-white bg-blue-100" />+ <div className="relative shrink-0 p-2.5">+ <FolderIcon className="size-4 text-blue-800" />+ </div>+ </div>+ <div className="flex min-w-0 flex-col text-sm">+ {folder && (+ <span className="truncate font-semibold leading-6 text-neutral-800">+ {folder.name}+ </span>+ )}+ <div className="flex items-center gap-1">+ <Globe className="size-3 shrink-0 text-neutral-400" />+ <span className="truncate text-neutral-500 transition-colors hover:text-neutral-700 hover:underline hover:underline-offset-2">+ {folder.type === "mega"+ ? "10,000+ links"+ : `${nFormatter(folderLinkCount, { full: true })} ${pluralize(+ "link",+ folderLinkCount,+ )}`}+ </span>+ </div>+ </div>+ </>+ )}+ </div>+ );+}++export function useShareDashboardModal(props: ShareDashboardModalInnerProps) {const [showShareDashboardModal, setShowShareDashboardModal] = useState(false);const ShareDashboardModalCallback = useCallback(() => {