The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Added "show my links only" feature + fixed a few bugs
Steven Teyd1336dc40959
diff --git a/components/app/links/link-filters.tsx b/components/app/links/link-filters.tsxindex 13b2726b15..3a263e4f71 100644--- a/components/app/links/link-filters.tsx+++ b/components/app/links/link-filters.tsx@@ -1,5 +1,5 @@import { useRouter } from "next/router";-import { useCallback, useEffect, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { nFormatter, setQueryString } from "@/lib/utils";import { ChevronRight, XCircle, Search } from "lucide-react";import useDomains from "@/lib/swr/use-domains";@@ -11,25 +11,33 @@ import useLinks from "@/lib/swr/use-links";import { LoadingSpinner } from "@/components/shared/icons";import useLinksCount from "@/lib/swr/use-links-count";import punycode from "punycode/";+import Switch from "@/components/shared/switch";+import { useSession } from "next-auth/react";export default function LinkFilters() {const { primaryDomain } = useDomains();const { data: domains } = useLinksCount({ groupBy: "domain" });const router = useRouter();- const { slug, search, domain, status } = router.query;+ const { slug, search, domain, userId } = router.query as {+ slug: string;+ search?: string;+ domain?: string;+ userId?: string;+ };const searchInputRef = useRef(); // this is a hack to clear the search input when the clear button is clickedreturn domains ? (- <div className="grid w-full gap-6 rounded-md bg-white p-5 lg:divide-y lg:divide-gray-300">- <div className="grid gap-3">+ <div className="grid w-full rounded-md bg-white px-5 lg:divide-y lg:divide-gray-300">+ <div className="grid gap-3 py-6"><div className="flex items-center justify-between"><h3 className="ml-1 mt-2 font-semibold">Filter Links</h3>- {(search || domain || status) && (+ {(search || domain || userId) && (<ClearButton searchInputRef={searchInputRef} />)}</div><SearchBox searchInputRef={searchInputRef} /></div>+ {slug && <MyLinksFilter />}<FilterGroupparam="domain"options={@@ -103,6 +111,27 @@ const SearchBox = ({ searchInputRef }: { searchInputRef }) => {);};+const MyLinksFilter = () => {+ const router = useRouter();+ const { userId } = router.query as { userId?: string };+ const { data: session } = useSession();++ return (+ <div className="flex items-center justify-between py-6">+ <label className="text-sm font-medium text-gray-600">+ Show my links only+ </label>+ <Switch+ fn={() =>+ // @ts-ignore+ setQueryString(router, "userId", userId ? "" : session?.user.id)+ }+ checked={userId ? true : false}+ />+ </div>+ );+};+const FilterGroup = ({param,options,@@ -121,7 +150,7 @@ const FilterGroup = ({const [collapsed, setCollapsed] = useState(false);return (- <fieldset className="pt-6">+ <fieldset className="py-6"><div className="flex h-8 items-center justify-between"><buttononClick={() => {diff --git a/components/app/modals/add-edit-link-modal/index.tsx b/components/app/modals/add-edit-link-modal/index.tsxindex b28fb35c23..d4735ecc65 100644--- a/components/app/modals/add-edit-link-modal/index.tsx+++ b/components/app/modals/add-edit-link-modal/index.tsx@@ -563,10 +563,14 @@ function AddEditLinkButton({const target = e.target as HTMLElement;const existingModalBackdrop = document.getElementById("modal-backdrop");// only open modal with keyboard shortcut if:+ // - c is pressed+ // - user is not pressing cmd/ctrl + c// - user is not typing in an input or textarea// - there is no existing modal backdrop (i.e. no other modal is open)if (e.key === "c" &&+ !e.metaKey &&+ !e.ctrlKey &&target.tagName !== "INPUT" &&target.tagName !== "TEXTAREA" &&!existingModalBackdropdiff --git a/components/app/modals/link-qr-modal.tsx b/components/app/modals/link-qr-modal.tsxindex fd93c883e1..40c26b63e9 100644--- a/components/app/modals/link-qr-modal.tsx+++ b/components/app/modals/link-qr-modal.tsx@@ -144,6 +144,7 @@ function LinkQRModalHelper({<AdvancedSettingsqrData={qrData}setFgColor={setFgColor}+ showLogo={showLogo}setShowLogo={setShowLogo}/>@@ -156,7 +157,7 @@ function LinkQRModalHelper({error: "Failed to copy",});}}- className="flex items-center justify-center gap-2 rounded-md border border-black bg-black py-1.5 px-5 text-sm text-white transition-all hover:bg-white hover:text-black"+ className="flex items-center justify-center gap-2 rounded-md border border-black bg-black px-5 py-1.5 text-sm text-white transition-all hover:bg-white hover:text-black"><Clipboard className="h-4 w-4" /> Copy</button>@@ -180,7 +181,7 @@ function LinkQRModalHelper({);}-function AdvancedSettings({ qrData, setFgColor, setShowLogo }) {+function AdvancedSettings({ qrData, setFgColor, showLogo, setShowLogo }) {const { plan } = useProject();const [expanded, setExpanded] = useState(false);@@ -206,7 +207,7 @@ function AdvancedSettings({ qrData, setFgColor, setShowLogo }) {</button></div>{expanded && (- <div className="mt-4 grid gap-5 border-t border-b border-gray-200 bg-white px-4 py-8 sm:px-16">+ <div className="mt-4 grid gap-5 border-b border-t border-gray-200 bg-white px-4 py-8 sm:px-16"><div><labelhtmlFor="logo-toggle"@@ -218,6 +219,7 @@ function AdvancedSettings({ qrData, setFgColor, setShowLogo }) {<div className="mt-1 flex items-center space-x-2"><Switchfn={setShowLogo}+ checked={showLogo}trackDimensions="h-6 w-12"thumbDimensions="w-5 h-5"thumbTranslate="translate-x-6"@@ -237,6 +239,7 @@ function AdvancedSettings({ qrData, setFgColor, setShowLogo }) {<div className="pointer-events-none mt-1 flex cursor-not-allowed items-center space-x-2 sm:pointer-events-auto"><Switchfn={setShowLogo}+ checked={showLogo}trackDimensions="h-6 w-12"thumbDimensions="w-5 h-5"thumbTranslate="translate-x-6"@@ -340,7 +343,7 @@ function QrDropdown({ download, qrData, showLogo, logo }) {><buttononClick={() => setOpenPopover(!openPopover)}- className="flex w-full items-center justify-center gap-2 rounded-md border border-black bg-black py-1.5 px-5 text-sm text-white transition-all hover:bg-white hover:text-black"+ className="flex w-full items-center justify-center gap-2 rounded-md border border-black bg-black px-5 py-1.5 text-sm text-white transition-all hover:bg-white hover:text-black"><Download />Exportdiff --git a/components/home/pricing.tsx b/components/home/pricing.tsxindex 7b76467c97..da74255a9f 100644--- a/components/home/pricing.tsx+++ b/components/home/pricing.tsx@@ -153,10 +153,10 @@ const Pricing = ({ homePage }: { homePage?: boolean }) => {/><Switchfn={setAnnualBilling}+ checked={annualBilling}trackDimensions="h-6 w-12"thumbDimensions="h-5 w-5"thumbTranslate="translate-x-6"- checked={annualBilling}/><p className="text-gray-600">Billed Annually</p><span className="absolute -right-12 -top-8 rounded-full bg-purple-200 px-3 py-1 text-sm text-purple-700 sm:-right-[9.5rem] sm:-top-2">diff --git a/components/shared/switch.tsx b/components/shared/switch.tsxindex 2c8cb81a17..d8232928e8 100644--- a/components/shared/switch.tsx+++ b/components/shared/switch.tsx@@ -19,7 +19,7 @@ const Switch = ({}) => {return (<SwitchPrimitive.Root- defaultChecked={checked}+ checked={checked}onCheckedChange={(checked) => fn(checked)}disabled={disabled}className={cx(diff --git a/components/stats/toggle.tsx b/components/stats/toggle.tsxindex c610d12b38..a82b7386e3 100644--- a/components/stats/toggle.tsx+++ b/components/stats/toggle.tsx@@ -59,7 +59,7 @@ export default function Toggle({</a><div className="flex items-center">{!basePath.startsWith("/stats") && key !== "_root" && (- <SharePopover domain={domain} />+ <SharePopover />)}<Popovercontent={@@ -113,26 +113,28 @@ export default function Toggle({);}-const SharePopover = ({ domain }: { domain: string }) => {+const SharePopover = () => {const router = useRouter();- const { slug, key } = router.query as {- slug?: string;+ const { key } = router.query as {key: string;};const [openSharePopover, setopenSharePopoverPopover] = useState(false);- const { endpoint, queryString } = useEndpoint(domain);+ const { endpoint, domain } = useEndpoint();const { data: { publicStats } = {} } = useSWR<{ publicStats: boolean }>(- endpoint + queryString,+ `${endpoint}?domain=${domain}`,fetcher,);+ const [updating, setUpdating] = useState(false);+const handleChange = async () => {toast.promise(new Promise<void>(async (resolve) => {- const res = await fetch(endpoint, {+ setUpdating(true);+ const res = await fetch(`${endpoint}?domain=${domain}`, {method: "PUT",headers: {"Content-Type": "application/json",@@ -142,8 +144,11 @@ const SharePopover = ({ domain }: { domain: string }) => {}),});if (res.status === 200) {- mutate(endpoint);+ mutate(`${endpoint}?domain=${domain}`);+ // artificial delay to sync toast with the switch change+ await new Promise((r) => setTimeout(r, 200));}+ setUpdating(false);resolve();}),{@@ -168,7 +173,11 @@ const SharePopover = ({ domain }: { domain: string }) => {<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={publicStats} fn={handleChange} />+ <Switch+ checked={publicStats}+ fn={handleChange}+ disabled={updating}+ /></div><p className="text-gray-500">Making stats public will allow anyone with the link to see thediff --git a/lib/auth.ts b/lib/auth.tsindex 77cffa44ae..22d6edb19c 100644--- a/lib/auth.ts+++ b/lib/auth.ts@@ -104,7 +104,8 @@ const withProjectAuth =}// if the action doesn't need to be gated for GET requests, return handler now- if (req.method === "GET" && excludeGet) return handler(req, res, project);+ if (req.method === "GET" && excludeGet)+ return handler(req, res, project, session);if (needNotExceededUsage && project.usage > project.usageLimit) {return res.status(403).end("Unauthorized: Usage limits exceeded.");diff --git a/lib/hooks/use-endpoint.ts b/lib/hooks/use-endpoint.tsindex 4c14c4efaa..5653a0b555 100644--- a/lib/hooks/use-endpoint.ts+++ b/lib/hooks/use-endpoint.ts@@ -41,7 +41,7 @@ export default function useEndpoint(staticDomain?: string) {};}- // Public stats page, e.g. dub.sh/stats/github+ // Public stats page, e.g. dub.sh/stats/github, stey.me/stats/weathergptreturn {basePath: `/stats/${key}`,domain: staticDomain,diff --git a/pages/api/projects/[slug]/links/count.ts b/pages/api/projects/[slug]/links/count.tsindex 6533748535..3c097223f7 100644--- a/pages/api/projects/[slug]/links/count.ts+++ b/pages/api/projects/[slug]/links/count.ts@@ -1,12 +1,14 @@import { withProjectAuth } from "@/lib/auth";import { getLinksCount } from "@/lib/api/links";-export default withProjectAuth(async (req, res, project) => {+export default withProjectAuth(async (req, res, project, session) => {// GET /api/projects/[slug]/domains/[domain]/links/count – count the number of links for a projectif (req.method === "GET") {+ const { userId } = req.query as { userId?: string };const count = await getLinksCount({req,projectId: project.id,+ userId,});return res.status(200).json(count);} else {diff --git a/pages/api/projects/[slug]/links/index.ts b/pages/api/projects/[slug]/links/index.tsindex c5b623ad22..683e26ec37 100644--- a/pages/api/projects/[slug]/links/index.ts+++ b/pages/api/projects/[slug]/links/index.ts@@ -28,6 +28,7 @@ export default withProjectAuth(tag,search,sort,+ // @ts-ignoreuserId,});return res.status(200).json(response);diff --git a/tsconfig.json b/tsconfig.jsonindex 8a09964213..5039d31128 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -1,30 +1,16 @@{"compilerOptions": {"target": "es5",- "lib": [- "dom",- "dom.iterable",- "esnext"- ],+ "lib": ["dom", "dom.iterable", "esnext"],"allowJs": true,"skipLibCheck": true,"baseUrl": ".","paths": {- "@/components/*": [- "components/*"- ],- "@/pages/*": [- "pages/*"- ],- "@/lib/*": [- "lib/*"- ],- "@/styles/*": [- "styles/*"- ],- "contentlayer/generated": [- "./.contentlayer/generated"- ]+ "@/components/*": ["components/*"],+ "@/pages/*": ["pages/*"],+ "@/lib/*": ["lib/*"],+ "@/styles/*": ["styles/*"],+ "contentlayer/generated": ["./.contentlayer/generated"]},"downlevelIteration": true,"forceConsistentCasingInFileNames": true,@@ -44,13 +30,6 @@// }// ],// "strictNullChecks": true- ,- "plugins": [- {- "name": "next"- }- ],- "strictNullChecks": true},"include": ["next-env.d.ts",@@ -58,10 +37,6 @@"**/*.tsx"// TODO: Ditto from above//".next/types/**/*.ts"- ,- ".next/types/**/*.ts"],- "exclude": [- "node_modules"- ]+ "exclude": ["node_modules"]}