The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add tag-based analytics
Steven Tey30a34ffb08dc
diff --git a/apps/web/app/api/cron/links/delete/route.ts b/apps/web/app/api/cron/links/delete/route.tsindex fcd9fb2e6c..b2445b4257 100644--- a/apps/web/app/api/cron/links/delete/route.ts+++ b/apps/web/app/api/cron/links/delete/route.ts@@ -30,7 +30,7 @@ export async function POST(req: Request) {return new Response("Link claimed. Skipping...", { status: 200 });}- await deleteLink(link);+ await deleteLink(link.id);return new Response("Link deleted.", { status: 200 });}diff --git a/apps/web/app/api/cron/links/event/route.ts b/apps/web/app/api/cron/links/event/route.tsindex 2b04926d4c..58242ddb4c 100644--- a/apps/web/app/api/cron/links/event/route.ts+++ b/apps/web/app/api/cron/links/event/route.ts@@ -34,6 +34,9 @@ export async function POST(req: Request) {where: {id: linkId,},+ include: {+ tags: true,+ },});if (!link) {diff --git a/apps/web/app/api/links/[linkId]/route.ts b/apps/web/app/api/links/[linkId]/route.tsindex 3d1438486d..47eab36102 100644--- a/apps/web/app/api/links/[linkId]/route.ts+++ b/apps/web/app/api/links/[linkId]/route.ts@@ -105,7 +105,7 @@ export const PUT = withAuth(async ({ req, headers, project, link }) => {// DELETE /api/links/[linkId] – delete a linkexport const DELETE = withAuth(async ({ headers, link }) => {// link is guaranteed to exist because if not we will return 404- const response = await deleteLink(link!);+ const response = await deleteLink(link!.id);return NextResponse.json(response[0], {headers,diff --git a/apps/web/app/api/links/bulk/route.ts b/apps/web/app/api/links/bulk/route.tsindex e311b774fe..070dee26df 100644--- a/apps/web/app/api/links/bulk/route.ts+++ b/apps/web/app/api/links/bulk/route.ts@@ -1,7 +1,7 @@-import { exceededLimitError } from "@/lib/api/errors";-import { bulkCreateLinks, processLink } from "@/lib/api/links";+import { DubApiError, exceededLimitError } from "@/lib/api/errors";+import { bulkCreateLinks, combineTagIds, processLink } from "@/lib/api/links";import { withAuth } from "@/lib/auth";-import { DubApiError } from "@/lib/api/errors";+import prisma from "@/lib/prisma";import { LinkWithTagIdsProps } from "@/lib/types";import { bulkCreateLinksBodySchema } from "@/lib/zod/schemas/links";import { NextResponse } from "next/server";@@ -31,6 +31,23 @@ export const POST = withAuth(});}+ // check if any of the links have a defined key and the domain + key combination is the same+ const duplicates = links.filter(+ (link, index, self) =>+ link.key &&+ self+ .slice(index + 1)+ .some((l) => l.domain === link.domain && l.key === link.key),+ );+ if (duplicates.length > 0) {+ throw new DubApiError({+ code: "bad_request",+ message: `Duplicate links found: ${duplicates+ .map((link) => `${link.domain}/${link.key}`)+ .join(", ")}`,+ });+ }+const processedLinks = await Promise.all(links.map(async (link) =>processLink({@@ -42,11 +59,11 @@ export const POST = withAuth(),);- const validLinks = processedLinks+ let validLinks = processedLinks.filter(({ error }) => !error).map(({ link }) => link);- const errors = processedLinks+ let errorLinks = processedLinks.filter(({ error }) => error).map(({ link, error, code }) => ({link,@@ -54,10 +71,41 @@ export const POST = withAuth(code,}));+ // filter out tags that don't belong to the project+ const projectTags = await prisma.tag.findMany({+ where: {+ projectId: project.id,+ },+ select: {+ id: true,+ },+ });+ const projectTagIds = projectTags.map(({ id }) => id);+ validLinks.forEach((link, index) => {+ const combinedTagIds = combineTagIds({+ tagId: link.tagId,+ tagIds: link.tagIds,+ });+ const invalidTagIds = combinedTagIds.filter(+ (id) => !projectTagIds.includes(id),+ );+ if (invalidTagIds.length > 0) {+ // remove link from validLinks and add error to errorLinks+ validLinks = validLinks.filter((_, i) => i !== index);+ errorLinks.push({+ link,+ error: `Invalid tagIds detected: ${invalidTagIds.join(", ")}`,+ code: "unprocessable_entity",+ });+ }+ });+const validLinksResponse =validLinks.length > 0 ? await bulkCreateLinks({ links: validLinks }) : [];- return NextResponse.json([...validLinksResponse, ...errors], { headers });+ return NextResponse.json([...validLinksResponse, ...errorLinks], {+ headers,+ });},{needNotExceededLinks: true,diff --git a/apps/web/app/api/links/sync/route.ts b/apps/web/app/api/links/sync/route.tsindex 48d073b754..2aeffbd5e4 100644--- a/apps/web/app/api/links/sync/route.ts+++ b/apps/web/app/api/links/sync/route.ts@@ -1,8 +1,8 @@import { exceededLimitError } from "@/lib/api/errors";-import { bulkCreateLinks } from "@/lib/api/links";+import { propagateBulkLinkChanges } from "@/lib/api/links";import { withAuth } from "@/lib/auth";import prisma from "@/lib/prisma";-import { LinkProps, SimpleLinkProps } from "@/lib/types";+import { SimpleLinkProps } from "@/lib/types";import { NextResponse } from "next/server";// POST /api/links/sync – sync user's publicly created links to their accounts@@ -17,7 +17,7 @@ export const POST = withAuth(async ({ req, session, project }) => {return new Response("Invalid request body.", { status: 400 });}- const unclaimedLinks = (await Promise.all(+ const unclaimedLinks = await Promise.all(links.map(async (link) => {return await prisma.link.findUnique({where: {@@ -27,9 +27,12 @@ export const POST = withAuth(async ({ req, session, project }) => {},userId: null,},+ include: {+ tags: true,+ },});}),- )) as LinkProps[];+ ).then((links) => links.filter((link) => link !== null));if (unclaimedLinks.length === 0) {return new Response("No links created.", { status: 400 });@@ -50,7 +53,7 @@ export const POST = withAuth(async ({ req, session, project }) => {prisma.link.updateMany({where: {id: {- in: unclaimedLinks.map((link) => link.id),+ in: unclaimedLinks.map((link) => link!.id),},},data: {@@ -59,27 +62,14 @@ export const POST = withAuth(async ({ req, session, project }) => {publicStats: false,},}),- bulkCreateLinks({- links: unclaimedLinks.map((link) => ({- ...link,+ propagateBulkLinkChanges(+ unclaimedLinks.map((link) => ({+ ...link!,userId: session.user.id,projectId: project.id,publicStats: false,- tagIds: [],})),- skipPrismaCreate: true,- }),- prisma.project.update({- where: {- id: project.id,- },- data: {- // TODO: sync clicks usage as well- linksUsage: {- increment: unclaimedLinks.length,- },- },- }),+ ),]);return NextResponse.json(response);diff --git a/apps/web/lib/analytics.ts b/apps/web/lib/analytics.tsindex 8132ed71dc..b003fecefe 100644--- a/apps/web/lib/analytics.ts+++ b/apps/web/lib/analytics.ts@@ -89,6 +89,7 @@ export const VALID_ANALYTICS_FILTERS = ["os","referer","excludeRoot",+ "tagId",];export const getAnalytics = async ({diff --git a/apps/web/lib/api/domains.ts b/apps/web/lib/api/domains.tsindex ee6fe72dc4..e018361f09 100644--- a/apps/web/lib/api/domains.ts+++ b/apps/web/lib/api/domains.ts@@ -259,6 +259,7 @@ export async function deleteDomainAndLinks(key: true,url: true,projectId: true,+ tags: true,},}),]);@@ -279,15 +280,9 @@ export async function deleteDomainAndLinks(},deleted: true,}),- ...allLinks.map(({ id, key, url, projectId }) =>+ ...allLinks.map((link) =>recordLink({- link: {- id,- domain,- key,- url,- projectId,- },+ link,deleted: true,}),),diff --git a/apps/web/lib/api/links.ts b/apps/web/lib/api/links.tsindex 0592c05067..7ade251cc9 100644--- a/apps/web/lib/api/links.ts+++ b/apps/web/lib/api/links.ts@@ -46,7 +46,7 @@ export async function getLinksForProject({withTags,}: Omit<z.infer<typeof getLinksQuerySchema>, "projectSlug"> & {projectId: string;-}): Promise<LinkProps[]> {+}) {const combinedTagIds = combineTagIds({ tagId, tagIds });const links = await prisma.link.findMany({@@ -411,7 +411,7 @@ export async function processLink({}// only perform tag validity checks if:- // - not bulk creation (we do that check in bulkCreateLinks)+ // - not bulk creation (we do that check separately in the route itself)// - tagIds are present} else if (tagIds.length > 0) {const tags = await prisma.tag.findMany({@@ -431,7 +431,7 @@ export async function processLink({(tagId) => tags.find(({ id }) => tagId === id) === undefined,).join(", "),- status: 422,+ code: "unprocessable_entity",};}}@@ -488,7 +488,7 @@ export async function processLink({};}-function combineTagIds({+export function combineTagIds({tagId,tagIds,}: {@@ -569,7 +569,7 @@ export async function addLink(link: LinkWithTagIdsProps) {return {...response,tagId: tags?.[0]?.id ?? null, // backwards compatibility- tags: response.tags.map(({ tag }) => tag),+ tags,shortLink,qrCode: `https://api.dub.co/qr?url=${shortLink}`,};@@ -577,25 +577,22 @@ export async function addLink(link: LinkWithTagIdsProps) {export async function bulkCreateLinks({links,- skipPrismaCreate,}: {links: LinkWithTagIdsProps[];- skipPrismaCreate?: boolean;}) {if (links.length === 0) return [];- let createdLinks: LinkProps[] = [];- let linkTags: { tagId: string; linkId: string }[] = [];+ // create links via $transaction (because Prisma doesn't support nested createMany)+ // ref: https://github.com/prisma/prisma/issues/8131#issuecomment-997667070+ const createdLinks = await prisma.$transaction(+ links.map(({ tagId, tagIds, ...link }) => {+ const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =+ getParamsFromURL(link.url);- if (skipPrismaCreate) {- createdLinks = links;- } else {- await prisma.link.createMany({- data: links.map(({ tagId, tagIds, ...link }) => {- const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =- getParamsFromURL(link.url);+ const combinedTagIds = combineTagIds({ tagId, tagIds });- return {+ return prisma.link.create({+ data: {...link,title: truncate(link.title, 120),description: truncate(link.description, 240),@@ -606,54 +603,60 @@ export async function bulkCreateLinks({utm_content,expiresAt: link.expiresAt ? new Date(link.expiresAt) : null,geo: link.geo || undefined,- // note: we're creating linkTags separately cause you can't do- // nested createMany in Prisma: https://github.com/prisma/prisma/issues/5455- };- }),- skipDuplicates: true,- });-- createdLinks = (await Promise.all(- links.map(async (link) => {- const { key, domain, tagId, tagIds } = link;- const data = await prisma.link.findUnique({- where: {- domain_key: {- domain,- key,+ ...(combinedTagIds.length > 0 && {+ tags: {+ createMany: {+ data: combinedTagIds.map((tagId) => ({ tagId })),+ },+ },+ }),+ },+ include: {+ tags: {+ select: {+ tagId: true,+ tag: {+ select: {+ id: true,+ name: true,+ color: true,+ },+ },},},- });- if (!data) return null;- // combine tagIds for creation later- const combinedTagIds = combineTagIds({ tagId, tagIds });- linkTags.push(- ...combinedTagIds.map((tagId) => ({ tagId, linkId: data.id })),- );- return data;- }),- )) as LinkWithTagIdsProps[];- }+ },+ });+ }),+ );++ await propagateBulkLinkChanges(createdLinks);++ return createdLinks.map((link) => {+ const shortLink = linkConstructor({+ domain: link.domain,+ key: link.key,+ });+ const tags = link.tags.map(({ tag }) => tag);+ return {+ ...link,+ shortLink,+ tagId: tags?.[0]?.id ?? null, // backwards compatibility+ tags,+ qrCode: `https://api.dub.co/qr?url=${shortLink}`,+ };+ });+}+export async function propagateBulkLinkChanges(+ links: (LinkProps & { tags: { tagId: string }[] })[],+) {const pipeline = redis.pipeline();- // split links into domains+ // split links into domains for better write effeciency in Redisconst linksByDomain: Record<string, Record<string, RedisLinkProps>> = {};- const [validTagIds, ..._rest] = await Promise.all([- prisma.tag- .findMany({- where: {- id: {- in: linkTags.map(({ tagId }) => tagId),- },- },- select: {- id: true,- },- })- .then((tags) => tags.map(({ id }) => id)),- ...createdLinks.map(async (link) => {+ await Promise.all(+ links.map(async (link) => {const { domain, key } = link;if (!linksByDomain[domain]) {@@ -666,44 +669,27 @@ export async function bulkCreateLinks({// record link in Tinybirdawait recordLink({ link });}),- ]);+ );Object.entries(linksByDomain).forEach(([domain, links]) => {pipeline.hset(domain, links);});await Promise.all([+ // update Redispipeline.exec(),- // create link tags for valid tagIds- linkTags.length > 0 &&- prisma.linkTag.createMany({- data: linkTags.filter(({ tagId }) => validTagIds.includes(tagId)),- skipDuplicates: true,- }),- // update links usage+ // update links usage for projectprisma.project.update({where: {- id: createdLinks[0].projectId!, // this will always be present+ id: links[0].projectId!, // this will always be present},data: {linksUsage: {- increment: createdLinks.length,+ increment: links.length,},},}),]);-- return createdLinks.map((link) => {- const shortLink = linkConstructor({- domain: link.domain,- key: link.key,- });- return {- ...link,- shortLink,- qrCode: `https://api.dub.co/qr?url=${shortLink}`,- };- });}export async function editLink({@@ -842,13 +828,16 @@ export async function editLink({};}-export async function deleteLink(link: LinkProps) {+export async function deleteLink(linkId: string) {+ const link = await prisma.link.delete({+ where: {+ id: linkId,+ },+ include: {+ tags: true,+ },+ });return await Promise.all([- prisma.link.delete({- where: {- id: link.id,- },- }),redis.hdel(link.domain, link.key.toLowerCase()),recordLink({ link, deleted: true }),link.projectId &&diff --git a/apps/web/lib/tinybird.ts b/apps/web/lib/tinybird.tsindex c876e44d97..88a3125d2e 100644--- a/apps/web/lib/tinybird.ts+++ b/apps/web/lib/tinybird.ts@@ -108,7 +108,9 @@ export async function recordLink({link,deleted,}: {- link: Partial<LinkProps>;+ link: Partial<LinkProps> & {+ tags?: { tagId: string }[];+ };deleted?: boolean;}) {return await fetch(@@ -124,7 +126,7 @@ export async function recordLink({domain: link.domain,key: link.key,url: link.url,- tagIds: [],+ tagIds: link.tags?.map(({ tagId }) => tagId) || [],project_id: link.projectId || "",deleted: deleted ? 1 : 0,}),diff --git a/apps/web/lib/zod/schemas/analytics.ts b/apps/web/lib/zod/schemas/analytics.tsindex be5ed3b1ce..ba63aee166 100644--- a/apps/web/lib/zod/schemas/analytics.ts+++ b/apps/web/lib/zod/schemas/analytics.ts@@ -38,6 +38,10 @@ export const getAnalyticsQuerySchema = z.object({excludeRoot: booleanQuerySchema.optional().describe("Whether to exclude the root link from the response."),+ tagId: z+ .string()+ .optional()+ .describe("The tag ID to retrieve analytics for."),});export const getAnalyticsEdgeQuerySchema = getAnalyticsQuerySchema.required({diff --git a/apps/web/scripts/bulk-delete-links.ts b/apps/web/scripts/bulk-delete-links.tsindex 9fb8e455a9..217524cda3 100644--- a/apps/web/scripts/bulk-delete-links.ts+++ b/apps/web/scripts/bulk-delete-links.ts@@ -16,6 +16,7 @@ async function main() {key: true,url: true,projectId: true,+ tags: true,},});const response = await Promise.all([diff --git a/apps/web/scripts/sync-tag-analytics.ts b/apps/web/scripts/sync-tag-analytics.tsnew file mode 100644index 0000000000..3fea800dda--- /dev/null+++ b/apps/web/scripts/sync-tag-analytics.ts@@ -0,0 +1,24 @@+import prisma from "@/lib/prisma";+import { recordLink } from "@/lib/tinybird";+import { DUB_PROJECT_ID } from "@dub/utils";+import "dotenv-flow/config";++async function main() {+ const links = await prisma.link.findMany({+ where: {+ projectId: DUB_PROJECT_ID,+ tags: {+ some: {},+ },+ },+ include: {+ tags: true,+ },+ });++ const res = await Promise.all(links.map((link) => recordLink({ link })));++ console.log(res);+}++main();diff --git a/apps/web/ui/analytics/clicks.tsx b/apps/web/ui/analytics/clicks.tsxindex 559747ed59..2954c48de0 100644--- a/apps/web/ui/analytics/clicks.tsx+++ b/apps/web/ui/analytics/clicks.tsx@@ -1,4 +1,5 @@import { VALID_ANALYTICS_FILTERS } from "@/lib/analytics";+import useTags from "@/lib/swr/use-tags";import { Chart } from "@/ui/shared/icons";import { NumberTooltip, useRouterStuff } from "@dub/ui";import {@@ -16,11 +17,12 @@ import { AnalyticsContext } from ".";import BarChart from "./bar-chart";export default function Clicks() {- const { totalClicks } = useContext(AnalyticsContext);+ const { totalClicks, tagId } = useContext(AnalyticsContext);const searchParams = useSearchParams();const domain = searchParams?.get("domain");const key = searchParams?.get("key");const { queryParams } = useRouterStuff();+ const { tags } = useTags();return (<div className="max-w-4xl border border-gray-200 bg-white p-5 sm:rounded-lg sm:border-gray-100 sm:p-10 sm:shadow-lg">@@ -75,9 +77,27 @@ export default function Clicks() {<X className="h-4 w-4" /></Link>))}+ {tags && tagId && (+ <Link+ href={+ queryParams({+ del: "tagId",+ getNewPath: true,+ }) as string+ }+ className="flex items-center space-x-1 rounded-lg border border-gray-200 bg-gray-50 px-3 py-1 text-sm text-gray-500 transition-all hover:bg-gray-100"+ >+ <p>Tag</p>+ <strong className="text-gray-800">+ {tags.find((tag) => tag.id === tagId)?.name || tagId}+ </strong>+ <X className="h-4 w-4" />+ </Link>+ )}{VALID_ANALYTICS_FILTERS.map((filter) => {+ if (filter === "excludeRoot" || filter === "tagId") return null;const value = searchParams?.get(filter);- if (!value || filter === "excludeRoot") return null;+ if (!value) return null;return (<Linkkey={filter}diff --git a/apps/web/ui/analytics/index.tsx b/apps/web/ui/analytics/index.tsxindex ea8e28e6b3..fb66ab3379 100644--- a/apps/web/ui/analytics/index.tsx+++ b/apps/web/ui/analytics/index.tsx@@ -28,6 +28,7 @@ export const AnalyticsContext = createContext<{url?: string;queryString: string;interval: string;+ tagId?: string;totalClicks?: number;}>({basePath: "",@@ -56,6 +57,8 @@ export default function Analytics({key = searchParams?.get("key") || key;const interval = searchParams?.get("interval") || "24h";+ const tagId = searchParams?.get("tagId") ?? undefined;+const { basePath, domain, baseApiPath } = useMemo(() => {// Project link analytics page, e.g. app.dub.co/dub/analytics?domain=dub.sh&key=githubif (slug) {@@ -90,8 +93,9 @@ export default function Analytics({...(key && { key }),...availableFilterParams,...(interval && { interval }),+ ...(tagId && { tagId }),}).toString();- }, [slug, domain, key, searchParams, interval]);+ }, [slug, domain, key, searchParams, interval, tagId]);const { data: totalClicks } = useSWR<number>(`${baseApiPath}/clicks?${queryString}`,@@ -110,6 +114,7 @@ export default function Analytics({key: key ? decodeURIComponent(key) : undefined, // link key (e.g. github, weathergpt, etc.)url: staticUrl, // url for the link (only for public stats pages)interval, // time interval (e.g. 24h, 7d, 30d, etc.)+ tagId, // id of a single tagtotalClicks, // total clicks for the link}}>diff --git a/apps/web/ui/analytics/share-popover.tsx b/apps/web/ui/analytics/share-popover.tsxnew file mode 100644index 0000000000..f039eed082--- /dev/null+++ b/apps/web/ui/analytics/share-popover.tsx@@ -0,0 +1,128 @@+import {+ Copy,+ IconMenu,+ Popover,+ Switch,+ Tick,+ useOptimisticUpdate,+} from "@dub/ui";+import { linkConstructor } from "@dub/utils";+import { Share2 } from "lucide-react";+import { useContext, useState } from "react";+import { toast } from "sonner";+import { AnalyticsContext } from ".";++export default function SharePopover() {+ const [openSharePopover, setopenSharePopoverPopover] = useState(false);++ const { baseApiPath, queryString, domain, key } = useContext(+ AnalyticsContext,+ ) as {+ baseApiPath: string;+ queryString: string;+ domain: string;+ key: string; // coerce to string since <SharePopover is not shown if key is undefined)+ };++ const { data, isLoading, update } = useOptimisticUpdate<{+ publicStats: boolean;+ }>(`${baseApiPath}?${queryString}`, {+ loading: "Updating...",+ success: "Successfully updated stats page visibility!",+ error: "Something went wrong",+ });++ const handleUpdate = async (checked: boolean) => {+ const res = await fetch(`${baseApiPath}?${queryString}`, {+ method: "PUT",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ publicStats: checked,+ }),+ });+ if (!res.ok) {+ throw new Error("Failed to update email preferences");+ }+ if (res.status === 200) {+ checked &&+ navigator.clipboard.writeText(+ `https://${domain}/stats/${encodeURIComponent(key)}`,+ );+ }+ return { publicStats: checked };+ };++ const [copied, setCopied] = useState(false);++ if (!data) return null;++ return (+ <Popover+ content={+ <div className="w-full divide-y divide-gray-200 text-sm md:w-60">+ <div className="p-4">+ <p className="text-gray-500">Share stats for</p>+ <p className="truncate font-semibold text-gray-800">+ {linkConstructor({ key, domain, pretty: true })}+ </p>+ </div>+ <div className="p-4">+ <div className="mb-2 flex items-center justify-between">+ <p className="font-semibold text-gray-800">Public Stats Page</p>+ <Switch+ checked={data?.publicStats}+ loading={isLoading}+ fn={(checked: boolean) => {+ update(() => handleUpdate(checked), { publicStats: checked });+ }}+ />+ </div>+ <p className="text-gray-500">+ Making stats public will allow anyone with the link to see the+ stats for this short link.+ </p>+ </div>+ <div className="p-4">+ <p className="font-semibold text-gray-800">Share Link</p>+ <div className="divide-x-200 mt-2 flex items-center justify-between divide-x overflow-hidden rounded-md border border-gray-200 bg-gray-100">+ <div className="scrollbar-hide overflow-scroll pl-2">+ <p className="whitespace-nowrap text-gray-600">+ https://{domain}/stats/{encodeURIComponent(key)}+ </p>+ </div>+ <button+ className="h-8 flex-none border-l bg-white px-2 hover:bg-gray-50 active:bg-gray-100"+ onClick={() => {+ navigator.clipboard.writeText(+ `https://${domain}/stats/${encodeURIComponent(key)}`,+ );+ setCopied(true);+ toast.success("Copied to clipboard");+ setTimeout(() => setCopied(false), 3000);+ }}+ >+ {copied ? (+ <Tick className="h-4 w-4 text-gray-500" />+ ) : (+ <Copy className="h-4 w-4 text-gray-500" />+ )}+ </button>+ </div>+ </div>+ </div>+ }+ align="end"+ openPopover={openSharePopover}+ setOpenPopover={setopenSharePopoverPopover}+ >+ <button+ onClick={() => setopenSharePopoverPopover(!openSharePopover)}+ className="flex w-24 items-center justify-center space-x-2 rounded-md bg-white px-3 py-2.5 shadow transition-all duration-75 hover:shadow-md active:scale-95"+ >+ <IconMenu text="Share" icon={<Share2 className="h-4 w-4" />} />+ </button>+ </Popover>+ );+}diff --git a/apps/web/ui/analytics/tag-selector.tsx b/apps/web/ui/analytics/tag-selector.tsxnew file mode 100644index 0000000000..53fcb607c2--- /dev/null+++ b/apps/web/ui/analytics/tag-selector.tsx@@ -0,0 +1,71 @@+import useTags from "@/lib/swr/use-tags";+import { IconMenu, Popover, Tick, useRouterStuff } from "@dub/ui";+import { ChevronDown, Tag } from "lucide-react";+import Link from "next/link";+import { useContext, useState } from "react";+import { AnalyticsContext } from ".";+import TagBadge from "../links/tag-badge";++export default function TagSelector() {+ const { queryParams } = useRouterStuff();++ const { tags } = useTags();+ const { tagId: selectedTagId } = useContext(AnalyticsContext);++ const [openPopover, setOpenPopover] = useState(false);++ return tags && tags.length > 0 ? (+ <Popover+ content={+ <div className="grid w-full p-2 md:w-48">+ <Link+ href={+ queryParams({+ del: "tagId",+ getNewPath: true,+ }) as string+ }+ className="flex w-full items-center justify-between space-x-2 rounded-md p-2 hover:bg-gray-100 active:bg-gray-200"+ >+ <p className="text-sm">All tags</p>+ {!selectedTagId && <Tick className="h-4 w-4" aria-hidden="true" />}+ </Link>+ {tags.map((tag) => (+ <Link+ key={tag.id}+ href={+ queryParams({+ set: { tagId: tag.id },+ getNewPath: true,+ }) as string+ }+ className="flex w-full items-center justify-between space-x-2 rounded-md p-2 hover:bg-gray-100 active:bg-gray-200"+ >+ <TagBadge {...tag} />+ {selectedTagId === tag.id && (+ <Tick className="h-4 w-4" aria-hidden="true" />+ )}+ </Link>+ ))}+ </div>+ }+ openPopover={openPopover}+ setOpenPopover={setOpenPopover}+ >+ <button+ onClick={(o) => setOpenPopover(!o)}+ className="flex w-full items-center justify-between space-x-2 rounded-md bg-white px-3 py-2.5 shadow transition-all hover:shadow-md md:w-48"+ >+ <IconMenu+ text={tags.find(({ id }) => id === selectedTagId)?.name || "All tags"}+ icon={<Tag className="h-4 w-4" />}+ />+ <ChevronDown+ className={`h-5 w-5 text-gray-400 ${+ openPopover ? "rotate-180 transform" : ""+ } transition-all duration-75`}+ />+ </button>+ </Popover>+ ) : undefined;+}diff --git a/apps/web/ui/analytics/toggle.tsx b/apps/web/ui/analytics/toggle.tsxindex 1d8a433cfa..3405fcd84e 100644--- a/apps/web/ui/analytics/toggle.tsx+++ b/apps/web/ui/analytics/toggle.tsx@@ -5,15 +5,12 @@ import { DomainProps } from "@/lib/types";import {BadgeTooltip,BlurImage,- Copy,ExpandingArrow,IconMenu,Popover,- Switch,Tick,Tooltip,TooltipContent,- useOptimisticUpdate,useRouterStuff,useScroll,} from "@dub/ui";@@ -26,13 +23,14 @@ import {getApexDomain,linkConstructor,} from "@dub/utils";-import { Calendar, ChevronDown, Lock, Share2 } from "lucide-react";+import { Calendar, ChevronDown, Lock } from "lucide-react";import Link from "next/link";import { useParams, useSearchParams } from "next/navigation";import punycode from "punycode/";import { useContext, useMemo, useState } from "react";-import { toast } from "sonner";import { AnalyticsContext } from ".";+import SharePopover from "./share-popover";+import TagSelector from "./tag-selector";export default function Toggle() {const { slug } = useParams() as { slug?: string };@@ -104,8 +102,9 @@ export default function Toggle() {)}</div>)}- <div className="flex items-center">+ <div className="flex items-center gap-2">{!isPublicStatsPage && key && <SharePopover />}+ {!isPublicStatsPage && !key && <TagSelector />}<Popovercontent={<div className="grid w-full p-2 md:w-48">@@ -231,118 +230,3 @@ const DomainsFilterTooltip = ({ domains }: { domains: DomainProps[] }) => {</div>);};--const SharePopover = () => {- const [openSharePopover, setopenSharePopoverPopover] = useState(false);-- const { baseApiPath, queryString, domain, key } = useContext(- AnalyticsContext,- ) as {- baseApiPath: string;- queryString: string;- domain: string;- key: string; // coerce to string since <SharePopover is not shown if key is undefined)- };-- const { data, isLoading, update } = useOptimisticUpdate<{- publicStats: boolean;- }>(`${baseApiPath}?${queryString}`, {- loading: "Updating...",- success: "Successfully updated stats page visibility!",- error: "Something went wrong",- });-- const handleUpdate = async (checked: boolean) => {- const res = await fetch(`${baseApiPath}?${queryString}`, {- method: "PUT",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({- publicStats: checked,- }),- });- if (!res.ok) {- throw new Error("Failed to update email preferences");- }- if (res.status === 200) {- checked &&- navigator.clipboard.writeText(- `https://${domain}/stats/${encodeURIComponent(key)}`,- );- }- return { publicStats: checked };- };-- const [copied, setCopied] = useState(false);-- if (!data) return null;-- return (- <Popover- content={- <div className="w-full divide-y divide-gray-200 text-sm md:w-60">- <div className="p-4">- <p className="text-gray-500">Share stats for</p>- <p className="truncate font-semibold text-gray-800">- {linkConstructor({ key, domain, pretty: true })}- </p>- </div>- <div className="p-4">- <div className="mb-2 flex items-center justify-between">- <p className="font-semibold text-gray-800">Public Stats Page</p>- <Switch- checked={data?.publicStats}- loading={isLoading}- fn={(checked: boolean) => {- update(() => handleUpdate(checked), { publicStats: checked });- }}- />- </div>- <p className="text-gray-500">- Making stats public will allow anyone with the link to see the- stats for this short link.- </p>- </div>- <div className="p-4">- <p className="font-semibold text-gray-800">Share Link</p>- <div className="divide-x-200 mt-2 flex items-center justify-between divide-x overflow-hidden rounded-md border border-gray-200 bg-gray-100">- <div className="scrollbar-hide overflow-scroll pl-2">- <p className="whitespace-nowrap text-gray-600">- https://{domain}/stats/{encodeURIComponent(key)}- </p>- </div>- <button- className="h-8 flex-none border-l bg-white px-2 hover:bg-gray-50 active:bg-gray-100"- onClick={() => {- navigator.clipboard.writeText(- `https://${domain}/stats/${encodeURIComponent(key)}`,- );- setCopied(true);- toast.success("Copied to clipboard");- setTimeout(() => setCopied(false), 3000);- }}- >- {copied ? (- <Tick className="h-4 w-4 text-gray-500" />- ) : (- <Copy className="h-4 w-4 text-gray-500" />- )}- </button>- </div>- </div>- </div>- }- align="end"- openPopover={openSharePopover}- setOpenPopover={setopenSharePopoverPopover}- >- <button- onClick={() => setopenSharePopoverPopover(!openSharePopover)}- className="mr-2 flex w-24 items-center justify-center space-x-2 rounded-md bg-white px-3 py-2.5 shadow transition-all duration-75 hover:shadow-md active:scale-95"- >- <IconMenu text="Share" icon={<Share2 className="h-4 w-4" />} />- </button>- </Popover>- );-};