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.

Improved link filters, finalized some migration changes, added <PlanBadge />

Steven Tey81b9da857ada
diff --git a/components/app/links/link-card.tsx b/components/app/links/link-card.tsx
index 083684403d..f1e22842dc 100644
--- a/components/app/links/link-card.tsx
+++ b/components/app/links/link-card.tsx
@@ -13,8 +13,6 @@ import {
Archive,
Chart,
Delete,
- Edit,
- LoadingDots,
QR,
ThreeDots,
} from "@/components/shared/icons";
@@ -31,6 +29,7 @@ import {
} from "@/lib/utils";
import useIntersectionObserver from "@/lib/hooks/use-intersection-observer";
import useDomains from "@/lib/swr/use-domains";
+import { CopyPlus, Edit3 } from "lucide-react";
export default function LinkCard({ props }: { props: LinkProps }) {
const { key, domain, url, createdAt, archived, expiresAt } = props;
@@ -64,6 +63,26 @@ export default function LinkCard({ props }: { props: LinkProps }) {
const { setShowAddEditLinkModal, AddEditLinkModal } = useAddEditLinkModal({
props,
});
+
+ // Duplicate link Modal
+ const {
+ id: _,
+ createdAt: __,
+ updatedAt: ___,
+ userId: ____,
+ ...propsToDuplicate
+ } = props;
+ const {
+ setShowAddEditLinkModal: setShowDuplicateLinkModal,
+ AddEditLinkModal: DuplicateLinkModal,
+ } = useAddEditLinkModal({
+ duplicateProps: {
+ ...propsToDuplicate,
+ key: `${key}-copy`,
+ clicks: 0,
+ },
+ });
+
const { setShowArchiveLinkModal, ArchiveLinkModal } = useArchiveLinkModal({
props,
archived: !archived,
@@ -82,6 +101,7 @@ export default function LinkCard({ props }: { props: LinkProps }) {
>
<LinkQRModal />
<AddEditLinkModal />
+ <DuplicateLinkModal />
<ArchiveLinkModal />
<DeleteLinkModal />
{/* <div className="absolute top-0 left-0 flex h-full w-1.5 flex-col overflow-hidden rounded-l-lg">
@@ -185,7 +205,7 @@ export default function LinkCard({ props }: { props: LinkProps }) {
<div className="w-full cursor-not-allowed p-2 text-left text-sm font-medium text-gray-300 transition-all duration-75">
<IconMenu
text="Edit"
- icon={<Edit className="h-4 w-4" />}
+ icon={<Edit3 className="h-4 w-4" />}
/>
</div>
</Tooltip>
@@ -197,7 +217,41 @@ export default function LinkCard({ props }: { props: LinkProps }) {
}}
className="w-full rounded-md p-2 text-left text-sm font-medium text-gray-500 transition-all duration-75 hover:bg-gray-100"
>
- <IconMenu text="Edit" icon={<Edit className="h-4 w-4" />} />
+ <IconMenu
+ text="Edit"
+ icon={<Edit3 className="h-4 w-4" />}
+ />
+ </button>
+ )}
+ {slug && exceededUsage ? (
+ <Tooltip
+ content={
+ <TooltipContent
+ title="Your project has exceeded its usage limit. We're still collecting data on your existing links, but you need to upgrade to edit them."
+ cta="Upgrade"
+ ctaLink={`/${slug}/settings/billing`}
+ />
+ }
+ >
+ <div className="w-full cursor-not-allowed p-2 text-left text-sm font-medium text-gray-300 transition-all duration-75">
+ <IconMenu
+ text="Duplicate"
+ icon={<CopyPlus className="h-4 w-4" />}
+ />
+ </div>
+ </Tooltip>
+ ) : (
+ <button
+ onClick={() => {
+ setOpenPopover(false);
+ setShowDuplicateLinkModal(true);
+ }}
+ className="w-full rounded-md p-2 text-left text-sm font-medium text-gray-500 transition-all duration-75 hover:bg-gray-100"
+ >
+ <IconMenu
+ text="Duplicate"
+ icon={<CopyPlus className="h-4 w-4" />}
+ />
</button>
)}
<button
diff --git a/components/app/links/link-filters/index.tsx b/components/app/links/link-filters.tsx
similarity index 88%
rename from components/app/links/link-filters/index.tsx
rename to components/app/links/link-filters.tsx
index b172febb0a..0341fa512a 100644
--- a/components/app/links/link-filters/index.tsx
+++ b/components/app/links/link-filters.tsx
@@ -7,9 +7,13 @@ import { AnimatePresence, motion } from "framer-motion";
import { SWIPE_REVEAL_ANIMATION_SETTINGS } from "@/lib/constants";
import { useDebouncedCallback } from "use-debounce";
import Link from "next/link";
+import useLinks from "@/lib/swr/use-links";
+import { LoadingSpinner } from "@/components/shared/icons";
+import useLinksCount from "@/lib/swr/use-links-count";
export default function LinkFilters() {
- const { domains } = useDomains({ includeLinkCount: true });
+ const { primaryDomain } = useDomains();
+ const { data: domains } = useLinksCount({ groupBy: "domain" });
const router = useRouter();
const { slug, search, domain, status } = router.query;
const searchInputRef = useRef(); // this is a hack to clear the search input when the clear button is clicked
@@ -27,10 +31,14 @@ export default function LinkFilters() {
</div>
<FilterGroup
param="domain"
- options={domains?.map(({ slug, _count }) => ({
- value: slug,
- count: _count.links,
- }))}
+ options={
+ domains.length === 0
+ ? [{ value: primaryDomain, count: 0 }]
+ : domains.map(({ domain, _count }) => ({
+ value: domain,
+ count: _count,
+ }))
+ }
cta={{
type: "link",
text: "Add a domain",
@@ -49,11 +57,16 @@ const SearchBox = ({ searchInputRef }: { searchInputRef }) => {
const debounced = useDebouncedCallback((value) => {
setQueryString(router, "search", value);
}, 500);
+ const { isValidating } = useLinks();
return (
<div className="relative">
<div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
- <Search className="h-4 w-4 text-gray-400" />
+ {isValidating ? (
+ <LoadingSpinner />
+ ) : (
+ <Search className="h-4 w-4 text-gray-400" />
+ )}
</div>
<input
ref={searchInputRef}
diff --git a/components/app/links/link-filters/search-bar.tsx b/components/app/links/link-filters/search-bar.tsx
deleted file mode 100644
index 4b80f3a65f..0000000000
--- a/components/app/links/link-filters/search-bar.tsx
+++ /dev/null
@@ -1,72 +0,0 @@
-import { useRouter } from "next/router";
-import useSWR from "swr";
-import { fetcher, getQueryString } from "@/lib/utils";
-import { useDebounce } from "use-debounce";
-import { LinkProps } from "@/lib/types";
-import { LoadingSpinner, Search } from "@/components/shared/icons";
-import { useState } from "react";
-
-export default function SearchBar() {
- const router = useRouter();
- const { slug } = router.query as {
- slug: string;
- };
- const { search } = router.query as { page?: string; search?: string };
- const { isValidating } = useSWR<LinkProps[]>(
- slug
- ? `/api/projects/${slug}/links${getQueryString(router)}`
- : `/api/links${getQueryString(router)}`,
- fetcher,
- {
- // disable this because it keeps refreshing the state of the modal when its open
- revalidateOnFocus: false,
- },
- );
- const [focused, setFocused] = useState(false);
- return (
- <div className="relative mx-2 mt-10 rounded-md shadow-sm sm:max-w-screen-lg lg:mx-auto">
- <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-4">
- {focused && search && isValidating ? (
- <LoadingSpinner />
- ) : (
- <Search className="h-5 w-5 text-gray-400" />
- )}
- </div>
- <input
- type="text"
- name="search"
- autoComplete="off"
- onFocus={() => setFocused(true)}
- onBlur={() => setFocused(false)}
- value={search || ""}
- onChange={(e) => {
- if (e.target.value === "") {
- delete router.query.search;
- router.replace(
- {
- query: {
- ...router.query,
- },
- },
- undefined,
- { shallow: true },
- );
- } else {
- router.replace(
- {
- query: {
- ...router.query,
- search: e.target.value,
- },
- },
- undefined,
- { shallow: true },
- );
- }
- }}
- className="block h-11 w-full rounded-md border-gray-200 pl-11 text-sm text-gray-600 transition-all placeholder:text-gray-400 focus:border-black focus:ring-0"
- placeholder="Search..."
- />
- </div>
- );
-}
diff --git a/components/app/links/link-filters/status-filter.tsx b/components/app/links/link-filters/status-filter.tsx
deleted file mode 100644
index 46163f80f4..0000000000
--- a/components/app/links/link-filters/status-filter.tsx
+++ /dev/null
@@ -1,133 +0,0 @@
-import { useRouter } from "next/router";
-import { useMemo, useState } from "react";
-import IconMenu from "@/components/shared/icon-menu";
-import { ChevronDown, Tick } from "@/components/shared/icons";
-import Popover from "@/components/shared/popover";
-
-const statuses = [
- {
- display: "Active",
- slug: "active",
- color: "bg-green-500",
- },
- {
- display: "Expired",
- slug: "expired",
- color: "bg-amber-500",
- },
- {
- display: "Archived",
- slug: "archived",
- color: "bg-gray-400",
- },
-];
-
-const statusArrToStr = (newStatusArr: string[]) => {
- if (
- ["active", "expired", "archived"].every((s) => newStatusArr.includes(s))
- ) {
- return "all";
- } else if (newStatusArr.length === 0) {
- return "none";
- } else if (newStatusArr.includes("active") && newStatusArr.length === 1) {
- return "default";
- } else {
- return newStatusArr.join(",");
- }
-};
-
-export default function StatusFilter() {
- const [openPopover, setOpenPopover] = useState(false);
- const router = useRouter();
- const { status } = router.query as { status?: string };
- const selectedStatus = useMemo(() => {
- if (!status) {
- return ["active"];
- } else if (status === "all" || status === "none") {
- return ["active", "expired", "archived"];
- } else {
- return status.split(",");
- }
- }, [status]);
-
- return (
- <Popover
- content={
- <div className="w-full p-2 md:w-44">
- {statuses.map(({ display, slug, color }) => (
- <button
- key={slug}
- onClick={() => {
- let newStatusArr;
- if (selectedStatus.includes(slug)) {
- if (status === "none") {
- newStatusArr = [slug];
- } else {
- newStatusArr = selectedStatus.filter((s) => s !== slug);
- }
- } else {
- newStatusArr = [...selectedStatus, slug];
- }
- let newQuery;
- if (statusArrToStr(newStatusArr) === "default") {
- delete router.query.status;
- newQuery = { ...router.query };
- } else {
- newQuery = {
- ...router.query,
- status: statusArrToStr(newStatusArr),
- };
- }
- const { slug: omit, ...finalQuery } = newQuery;
- router.push({
- pathname: `/${router.query.slug || "links"}`,
- query: finalQuery,
- });
- }}
- className="flex w-full items-center justify-between rounded-md p-2 hover:bg-gray-100 active:bg-gray-200"
- >
- <IconMenu
- text={display}
- icon={<div className={`h-2 w-2 rounded-full ${color}`} />}
- />
- {(status === "all" ||
- (selectedStatus.includes(slug) && status !== "none")) && (
- <Tick className="h-4 w-4" aria-hidden="true" />
- )}
- </button>
- ))}
- </div>
- }
- openPopover={openPopover}
- setOpenPopover={setOpenPopover}
- >
- <button
- onClick={() => setOpenPopover(!openPopover)}
- className="flex w-full items-center justify-between space-x-2 rounded-md bg-white px-3 py-2.5 shadow transition-all duration-75 hover:shadow-md active:scale-95 sm:w-44"
- >
- <div className="flex items-center space-x-2 text-gray-700">
- <IconMenu
- text="Status"
- icon={
- <div className="flex -space-x-1">
- {statuses.map(({ slug, color }) => (
- <div
- key={slug}
- className={`h-3.5 w-3.5 rounded-full ${
- selectedStatus.includes(slug) ? color : "bg-gray-200"
- } border border-white`}
- />
- ))}
- </div>
- }
- />
- </div>
- <ChevronDown
- className={`h-5 w-5 text-gray-400 ${
- openPopover ? "rotate-180 transform" : ""
- } transition-all duration-75`}
- />
- </button>
- </Popover>
- );
-}
diff --git a/components/app/links/link-filters/user-filter.tsx b/components/app/links/link-filters/user-filter.tsx
deleted file mode 100644
index fa6de58a1d..0000000000
--- a/components/app/links/link-filters/user-filter.tsx
+++ /dev/null
@@ -1,103 +0,0 @@
-import { useRouter } from "next/router";
-import { useMemo, useState } from "react";
-import useSWR from "swr";
-import BlurImage from "@/components/shared/blur-image";
-import { ChevronDown, Search, X } from "@/components/shared/icons";
-import Popover from "@/components/shared/popover";
-import { UserProps } from "@/lib/types";
-import { fetcher } from "@/lib/utils";
-
-export default function UserFilter() {
- const [openPopover, setOpenPopover] = useState(false);
- const router = useRouter();
- const { slug } = router.query as { slug?: string };
- const { data: users } = useSWR<UserProps[]>(
- slug && `/api/projects/${slug}/users`,
- fetcher,
- {
- dedupingInterval: 30000,
- fallbackData: [],
- },
- );
- const { userId } = router.query as { userId?: string };
-
- const currentUser = useMemo(
- () => users.find((user) => user.id === userId) || null,
- [users, userId],
- );
-
- return (
- <Popover
- content={
- <div className="w-full p-2 md:w-56">
- {users.map(({ id, name, email }) => (
- <button
- key={id}
- onClick={() => {
- let newQuery;
- newQuery = {
- ...router.query,
- userId: id,
- };
- const { slug: omit, ...finalQuery } = newQuery;
- router.push({
- pathname: `/${router.query.slug}`,
- query: finalQuery,
- });
- }}
- className="flex w-full items-center space-x-2 rounded-md p-2 hover:bg-gray-100 active:bg-gray-200"
- >
- <BlurImage
- src={`https://avatar.vercel.sh/${email}`}
- alt={email}
- width={28}
- height={28}
- className="rounded-full"
- />
- <p className="truncate text-sm text-gray-700">{name || email}</p>
- </button>
- ))}
- </div>
- }
- openPopover={openPopover}
- setOpenPopover={setOpenPopover}
- >
- <button
- onClick={() => setOpenPopover(!openPopover)}
- className="flex w-full items-center justify-between space-x-1 rounded-md bg-white px-3 py-2 shadow transition-all duration-75 hover:shadow-md active:scale-95 md:w-56"
- >
- <div className="flex w-44 items-center space-x-2 text-gray-700">
- <Search className="h-4 w-4 shrink-0" />
- <p className="truncate text-sm">
- {currentUser?.name || currentUser?.email || "All Users..."}
- </p>
- </div>
- {currentUser ? (
- <div
- onClick={() => {
- let newQuery;
- newQuery = {
- ...router.query,
- };
- delete newQuery.userId;
- const { slug: omit, ...finalQuery } = newQuery;
- router.push({
- pathname: `/${router.query.slug}`,
- query: finalQuery,
- });
- }}
- className="rounded-full p-1 transition-all duration-75 hover:bg-gray-100 active:bg-gray-200"
- >
- <X className="h-4 w-4" />
- </div>
- ) : (
- <ChevronDown
- className={`h-5 w-5 cursor-pointer text-gray-400 ${
- openPopover ? "rotate-180 transform" : ""
- } transition-all duration-75`}
- />
- )}
- </button>
- </Popover>
- );
-}
diff --git a/components/app/links/links-container.tsx b/components/app/links/links-container.tsx
index 3e928fce7b..6f09b0adbd 100644
--- a/components/app/links/links-container.tsx
+++ b/components/app/links/links-container.tsx
@@ -1,9 +1,4 @@
-import { useRouter } from "next/router";
-import useSWR from "swr";
import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
-import useProject from "@/lib/swr/use-project";
-import { LinkProps } from "@/lib/types";
-import { fetcher, getQueryString } from "@/lib/utils";
import LinkCard from "./link-card";
import LinkCardPlaceholder from "./link-card-placeholder";
import LinkFilters from "./link-filters";
diff --git a/components/app/modals/add-edit-link-modal/index.tsx b/components/app/modals/add-edit-link-modal/index.tsx
index 10bbec33f8..666237858d 100644
--- a/components/app/modals/add-edit-link-modal/index.tsx
+++ b/components/app/modals/add-edit-link-modal/index.tsx
@@ -44,12 +44,14 @@ function AddEditLinkModal({
showAddEditLinkModal,
setShowAddEditLinkModal,
props,
+ duplicateProps,
hideXButton,
homepageDemo,
}: {
showAddEditLinkModal: boolean;
setShowAddEditLinkModal: Dispatch<SetStateAction<boolean>>;
props?: LinkProps;
+ duplicateProps?: LinkProps;
hideXButton?: boolean;
homepageDemo?: boolean;
}) {
@@ -64,19 +66,30 @@ function AddEditLinkModal({
const { domains, primaryDomain } = useDomains();
const [data, setData] = useState<LinkProps>(
- props || {
- ...DEFAULT_LINK_PROPS,
- domain: primaryDomain || "",
- key: "",
- url: "",
- },
+ props ||
+ duplicateProps || {
+ ...DEFAULT_LINK_PROPS,
+ domain: primaryDomain || "",
+ key: "",
+ url: "",
+ },
);
const { domain, key, url, password, proxy } = data;
const [debouncedKey] = useDebounce(key, 500);
useEffect(() => {
- if (debouncedKey.length > 0 && debouncedKey !== props?.key) {
+ /**
+ * Only check if key exists if:
+ * - modal is open
+ * - key is not empty
+ * - key is not the same as the original key
+ **/
+ if (
+ showAddEditLinkModal &&
+ debouncedKey.length > 0 &&
+ debouncedKey !== props?.key
+ ) {
fetch(
slug
? `/api/projects/${slug}/links/${debouncedKey}/exists?domain=${domain}`
@@ -553,10 +566,12 @@ function AddEditLinkButton({
export function useAddEditLinkModal({
props,
+ duplicateProps,
hideXButton,
homepageDemo,
}: {
props?: LinkProps;
+ duplicateProps?: LinkProps;
hideXButton?: boolean;
homepageDemo?: boolean;
} = {}) {
@@ -568,6 +583,7 @@ export function useAddEditLinkModal({
showAddEditLinkModal={showAddEditLinkModal}
setShowAddEditLinkModal={setShowAddEditLinkModal}
props={props}
+ duplicateProps={duplicateProps}
hideXButton={hideXButton}
homepageDemo={homepageDemo}
/>
@@ -576,6 +592,7 @@ export function useAddEditLinkModal({
showAddEditLinkModal,
setShowAddEditLinkModal,
props,
+ duplicateProps,
hideXButton,
homepageDemo,
]);
diff --git a/components/app/project-card.tsx b/components/app/project-card.tsx
index fe4725f482..fa2caa766f 100644
--- a/components/app/project-card.tsx
+++ b/components/app/project-card.tsx
@@ -6,12 +6,14 @@ import Tooltip, { TooltipContent } from "@/components/shared/tooltip";
import { ProjectWithDomainProps } from "@/lib/types";
import { fetcher, nFormatter } from "@/lib/utils";
import { BarChart2, Globe, Link2 } from "lucide-react";
+import PlanBadge from "./settings/plan-badge";
export default function ProjectCard({
name,
slug,
logo,
usage,
+ plan,
domains,
primaryDomain,
}: ProjectWithDomainProps) {
@@ -25,45 +27,48 @@ export default function ProjectCard({
href={`/${slug}`}
className="flex flex-col space-y-10 rounded-lg border border-gray-100 bg-white p-6 shadow transition-all hover:shadow-lg"
>
- <div className="flex items-center space-x-3">
- <BlurImage
- src={
- logo ||
- `https://www.google.com/s2/favicons?sz=64&domain_url=${primaryDomain?.slug}`
- }
- alt={slug}
- className="h-10 w-10 flex-shrink-0 overflow-hidden rounded-full"
- width={48}
- height={48}
- />
- <div>
- <h2 className="text-lg font-medium text-gray-700">{name}</h2>
- <div className="flex items-center">
- <p className="text-gray-500">{primaryDomain?.slug}</p>
- {primaryDomain?.verified ? (
- <Tooltip content="Verified domain">
- <div className="flex w-8 justify-center">
- <CheckCircleFill className="h-5 w-5 text-blue-500" />
- </div>
- </Tooltip>
- ) : (
- <Tooltip
- content={
- <TooltipContent
- title="This domain is not correctly configured. Please configure your domain to
+ <div className="flex items-start justify-between">
+ <div className="flex items-center space-x-3">
+ <BlurImage
+ src={
+ logo ||
+ `https://www.google.com/s2/favicons?sz=64&domain_url=${primaryDomain?.slug}`
+ }
+ alt={slug}
+ className="h-10 w-10 flex-shrink-0 overflow-hidden rounded-full"
+ width={48}
+ height={48}
+ />
+ <div>
+ <h2 className="text-lg font-medium text-gray-700">{name}</h2>
+ <div className="flex items-center">
+ <p className="text-gray-500">{primaryDomain?.slug}</p>
+ {primaryDomain?.verified ? (
+ <Tooltip content="Verified domain">
+ <div className="flex w-8 justify-center">
+ <CheckCircleFill className="h-5 w-5 text-blue-500" />
+ </div>
+ </Tooltip>
+ ) : (
+ <Tooltip
+ content={
+ <TooltipContent
+ title="This domain is not correctly configured. Please configure your domain to
start adding links."
- cta="Configure Domain"
- ctaLink={`/${slug}/settings`}
- />
- }
- >
- <div className="flex w-8 justify-center">
- <XCircleFill className="h-5 w-5 text-gray-300" />
- </div>
- </Tooltip>
- )}
+ cta="Configure Domain"
+ ctaLink={`/${slug}/settings`}
+ />
+ }
+ >
+ <div className="flex w-8 justify-center">
+ <XCircleFill className="h-5 w-5 text-gray-300" />
+ </div>
+ </Tooltip>
+ )}
+ </div>
</div>
</div>
+ <PlanBadge plan={plan} />
</div>
<div className="flex items-center space-x-4">
<div className="flex items-center space-x-2 text-gray-500">
diff --git a/components/app/settings/plan-badge.tsx b/components/app/settings/plan-badge.tsx
new file mode 100644
index 0000000000..165aa18a10
--- /dev/null
+++ b/components/app/settings/plan-badge.tsx
@@ -0,0 +1,19 @@
+export default function PlanBadge({
+ plan,
+}: {
+ plan: "free" | "pro" | "enterprise";
+}) {
+ return (
+ <span
+ className={`capitalize ${
+ plan === "enterprise"
+ ? "border-violet-600 bg-violet-600 text-white"
+ : plan === "pro"
+ ? "border-blue-500 bg-blue-500 text-white"
+ : "border-black bg-black text-white"
+ } rounded-full border px-2 py-0.5 text-xs font-medium`}
+ >
+ {plan}
+ </span>
+ );
+}
diff --git a/components/app/settings/plan-usage.tsx b/components/app/settings/plan-usage.tsx
index 823db3e614..15c2ef8dd5 100644
--- a/components/app/settings/plan-usage.tsx
+++ b/components/app/settings/plan-usage.tsx
@@ -12,6 +12,7 @@ import Tooltip from "@/components/shared/tooltip";
import { getFirstAndLastDay, nFormatter } from "@/lib/utils";
import useProject from "@/lib/swr/use-project";
import useDomains from "@/lib/swr/use-domains";
+import PlanBadge from "./plan-badge";
export default function PlanUsage() {
const router = useRouter();
@@ -47,17 +48,7 @@ export default function PlanUsage() {
<p className="text-sm text-gray-500">
You are currently on the{" "}
{plan ? (
- <span
- className={`capitalize ${
- plan === "enterprise"
- ? "border-violet-600 bg-violet-600 text-white"
- : plan === "pro"
- ? "border-blue-500 bg-blue-500 text-white"
- : "border-black bg-black text-white"
- } rounded-full border px-2 py-0.5 text-xs font-medium`}
- >
- {plan}
- </span>
+ <PlanBadge plan={plan} />
) : (
<span className="rounded-full bg-gray-200 px-2 py-0.5 text-xs text-gray-200">
load
diff --git a/components/layout/app/project-select.tsx b/components/layout/app/project-select.tsx
index 8fedd4cdc3..6ec117bc91 100644
--- a/components/layout/app/project-select.tsx
+++ b/components/layout/app/project-select.tsx
@@ -7,6 +7,7 @@ import { ChevronUpDown, PlusCircle, Tick } from "@/components/shared/icons";
import Popover from "@/components/shared/popover";
import { ProjectWithDomainProps } from "@/lib/types";
import useProjects from "@/lib/swr/use-projects";
+import PlanBadge from "@/components/app/settings/plan-badge";
export default function ProjectSelect() {
const { projects } = useProjects();
@@ -37,9 +38,15 @@ export default function ProjectSelect() {
image:
session?.user?.image ||
`https://avatars.dicebear.com/api/micah/${session?.user?.email}.svg`,
+ plan: "free",
};
}
- }, [slug, projects, session]);
+ }, [slug, projects, session]) as {
+ name: string;
+ slug: string;
+ image: string;
+ plan: "free" | "pro" | "enterprise";
+ };
const [openPopover, setOpenPopover] = useState(false);
@@ -68,7 +75,7 @@ export default function ProjectSelect() {
onClick={() => setOpenPopover(!openPopover)}
className="flex w-60 items-center justify-between rounded-lg bg-white p-1.5 text-left text-sm transition-all duration-75 hover:bg-gray-100 focus:outline-none active:bg-gray-200"
>
- <div className="flex items-center justify-start space-x-3 pr-2">
+ <div className="flex items-center space-x-3 pr-2">
<BlurImage
src={selected.image}
alt={selected.slug}
@@ -79,6 +86,7 @@ export default function ProjectSelect() {
<span className="truncate text-sm font-medium">
{selected.name}
</span>
+ {selected.slug !== "/" && <PlanBadge plan={selected.plan} />}
</div>
<ChevronUpDown className="h-4 w-4 text-gray-400" aria-hidden="true" />
</button>
@@ -95,7 +103,8 @@ function ProjectList({
selected: {
name: string;
slug: string;
- image?: string;
+ image: string;
+ plan: "free" | "pro" | "enterprise";
};
projects: ProjectWithDomainProps[];
setShowAddProjectModal?: (show: boolean) => void;
diff --git a/components/shared/icons/loading-spinner.module.css b/components/shared/icons/loading-spinner.module.css
index 8dc5706a2a..2b1ac0afe4 100644
--- a/components/shared/icons/loading-spinner.module.css
+++ b/components/shared/icons/loading-spinner.module.css
@@ -2,9 +2,9 @@
color: gray;
display: inline-block;
position: relative;
- width: 80px;
- height: 80px;
- transform: scale(0.3) translateX(-95px);
+ width: 70px;
+ height: 70px;
+ transform: scale(0.3) translateX(-90px) translateY(-5px);
}
.spinner div {
transform-origin: 40px 40px;
@@ -14,7 +14,7 @@
content: " ";
display: block;
position: absolute;
- top: 3px;
+ top: 5px;
left: 37px;
width: 6px;
height: 20px;
diff --git a/lib/api/links.ts b/lib/api/links.ts
index 0718fc0d64..8ce53ce0d0 100644
--- a/lib/api/links.ts
+++ b/lib/api/links.ts
@@ -4,6 +4,7 @@ import prisma from "@/lib/prisma";
import { LinkProps } from "@/lib/types";
import { redis } from "@/lib/upstash";
import { getParamsFromURL, isReservedKey, nanoid, truncate } from "@/lib/utils";
+import { NextApiRequest } from "next";
const getFiltersFromStatus = (status: string) => {
if (status === "all" || status === "none") {
@@ -71,23 +72,17 @@ export async function getLinksForProject({
sort?: "createdAt" | "clicks"; // always descending for both
userId?: string;
}): Promise<LinkProps[]> {
- console.log({ projectId, domain, status, tag, search, sort, userId });
const filters = getFiltersFromStatus(status);
return await prisma.link.findMany({
where: {
projectId,
...(domain && { domain }),
...(search && {
- OR: [{ key: { contains: search } }, { url: { contains: search } }],
+ key: { search },
+ url: { search },
}),
...filters,
// ...(tag && { tags: { has: tag } }),
- // ...(search && {
- // key: { search },
- // url: { search },
- // title: { search },
- // description: { search },
- // }),
...(userId && { userId }),
},
orderBy: {
@@ -97,6 +92,57 @@ export async function getLinksForProject({
});
}
+export async function getLinksCount({
+ req,
+ projectId,
+ userId,
+}: {
+ req: NextApiRequest;
+ projectId: string;
+ userId?: string;
+}) {
+ const { groupBy, search, domain } = req.query as {
+ groupBy?: "domain";
+ search?: string;
+ domain?: string;
+ };
+
+ if (groupBy) {
+ return await prisma.link.groupBy({
+ by: [groupBy],
+ where: {
+ projectId,
+ ...(userId && { userId }),
+ ...(search && {
+ key: { search },
+ url: { search },
+ }),
+ ...(domain &&
+ groupBy !== "domain" && {
+ domain,
+ }),
+ },
+ _count: true,
+ orderBy: {
+ _count: {
+ [groupBy]: "desc",
+ },
+ },
+ });
+ } else {
+ return await prisma.link.count({
+ where: {
+ projectId,
+ ...(userId && { userId }),
+ ...(search && {
+ key: { search },
+ url: { search },
+ }),
+ },
+ });
+ }
+}
+
export async function getRandomKey(domain: string): Promise<string> {
/* recursively get random key till it gets one that's avaialble */
const key = nanoid();
diff --git a/lib/swr/use-domains.ts b/lib/swr/use-domains.ts
index 85164b0466..659c2b4a48 100644
--- a/lib/swr/use-domains.ts
+++ b/lib/swr/use-domains.ts
@@ -4,37 +4,40 @@ import useSWR from "swr";
import { DomainProps } from "@/lib/types";
import { fetcher } from "@/lib/utils";
-export default function useDomains({
- domain,
- includeLinkCount,
-}: { domain?: string; includeLinkCount?: boolean } = {}) {
+export default function useDomains({ domain }: { domain?: string } = {}) {
const router = useRouter();
let { slug } = router.query as {
slug: string;
};
- if (!slug && router.isReady) {
- slug = "dub";
- }
-
- const { data: domains, error } = useSWR<DomainProps[]>(
- slug &&
- `/api/projects/${slug}/domains${
- includeLinkCount ? "?includeLinkCount=true" : ""
- }`,
+ const { data, error } = useSWR<DomainProps[]>(
+ slug && `/api/projects/${slug}/domains`,
fetcher,
{
- dedupingInterval: 30000,
+ dedupingInterval: 60000,
},
);
+ const domains = useMemo(() => {
+ if (router.isReady) {
+ return slug
+ ? data
+ : ([
+ {
+ slug: "dub.sh",
+ verified: true,
+ primary: true,
+ target: "https://dub.sh",
+ type: "redirect",
+ },
+ ] as DomainProps[]);
+ }
+ }, [data, router.isReady]);
+
return {
domains,
- primaryDomain: useMemo(
- () => domains?.find((domain) => domain.primary)?.slug,
- [domains],
- ),
+ primaryDomain: domains?.find((domain) => domain.primary)?.slug,
verified: domain
? // If a domain is passed, check if it's verified
domains?.find((d) => d.slug === domain)?.verified
diff --git a/lib/swr/use-links-count.ts b/lib/swr/use-links-count.ts
new file mode 100644
index 0000000000..0fd3ff00e8
--- /dev/null
+++ b/lib/swr/use-links-count.ts
@@ -0,0 +1,36 @@
+import { useRouter } from "next/router";
+import useSWR from "swr";
+import { fetcher, getQueryString } from "@/lib/utils";
+
+export default function useLinksCount({
+ groupBy,
+}: { groupBy?: "domain" } = {}) {
+ const router = useRouter();
+
+ const { slug } = router.query as {
+ slug: string;
+ };
+
+ const { data, error } = useSWR<
+ {
+ [groupBy]: string;
+ _count: number;
+ }[]
+ >(
+ router.isReady &&
+ `${
+ slug ? `/api/projects/${slug}/links/count` : `/api/links/count`
+ }${getQueryString(router, groupBy ? { groupBy } : undefined)}`,
+ fetcher,
+ {
+ dedupingInterval: 10000,
+ keepPreviousData: true,
+ },
+ );
+
+ return {
+ data,
+ loading: !error && !data,
+ error,
+ };
+}
diff --git a/lib/swr/use-links.ts b/lib/swr/use-links.ts
index b81c91a93d..b1d30464e0 100644
--- a/lib/swr/use-links.ts
+++ b/lib/swr/use-links.ts
@@ -10,7 +10,7 @@ export default function useLinks() {
slug: string;
};
- const { data: links } = useSWR<LinkProps[]>(
+ const { data: links, isValidating } = useSWR<LinkProps[]>(
router.isReady &&
(slug
? `/api/projects/${slug}/links${getQueryString(router)}`
@@ -26,5 +26,6 @@ export default function useLinks() {
return {
links,
loading: links ? false : true,
+ isValidating,
};
}
diff --git a/lib/types.ts b/lib/types.ts
index 9baaa64538..da5cdfaa03 100644
--- a/lib/types.ts
+++ b/lib/types.ts
@@ -22,9 +22,10 @@ export interface LinkProps {
android: string | null;
clicks: number;
- userId: string;
+ userId?: string;
- createdAt: Date;
+ createdAt?: Date;
+ updatedAt?: Date;
}
export interface ProjectProps {
@@ -51,13 +52,6 @@ export interface ProjectWithDomainProps extends ProjectProps {
primaryDomain: DomainProps;
}
-export interface UsageProps {
- usage: number;
- usageLimit: number;
- plan: "free" | "pro" | "enterprise";
- billingCycleStart?: number;
-}
-
export interface UserProps {
id: string;
name: string;
@@ -89,7 +83,4 @@ export interface DomainProps {
primary: boolean;
target?: string;
type: "redirect" | "rewrite";
- _count?: {
- links: number;
- };
}
diff --git a/lib/utils.ts b/lib/utils.ts
index 08b7b37cc4..f9317b240d 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -223,12 +223,16 @@ export const getDomainWithoutWWW = (url: string) => {
}
};
-export const getQueryString = (router: NextRouter) => {
+export const getQueryString = (
+ router: NextRouter,
+ opts: Record<string, string>,
+) => {
// here, we omit the slug from the query string because
// for some reason it breaks the router because of middleware rewrites
const { slug, ...queryWithoutSlug } = router.query as Record<string, string>;
const queryString = new URLSearchParams({
...queryWithoutSlug,
+ ...opts,
}).toString();
return `${queryString ? "?" : ""}${queryString}`;
};
diff --git a/next.config.js b/next.config.js
index 34479c5cc9..91cfc6b96f 100644
--- a/next.config.js
+++ b/next.config.js
@@ -1,6 +1,6 @@
/** @type {import('next').NextConfig} */
module.exports = {
- reactStrictMode: true,
+ reactStrictMode: false,
images: {
domains: [
"www.google.com",
diff --git a/package.json b/package.json
index 1bf6646ed5..b81d644a70 100644
--- a/package.json
+++ b/package.json
@@ -63,7 +63,7 @@
"react-spring": "^9.5.5",
"react-textarea-autosize": "^8.4.0",
"stripe": "^11.1.0",
- "swr": "^1.3.0",
+ "swr": "^2.1.5",
"tailwind-scrollbar-hide": "^1.1.7",
"topojson-client": "^3.1.0",
"use-debounce": "^8.0.4"
diff --git a/pages/api/links/count.ts b/pages/api/links/count.ts
new file mode 100644
index 0000000000..43cc66fe99
--- /dev/null
+++ b/pages/api/links/count.ts
@@ -0,0 +1,24 @@
+import { NextApiRequest, NextApiResponse } from "next";
+import { Session, withUserAuth } from "@/lib/auth";
+import prisma from "@/lib/prisma";
+import { DUB_PROJECT_ID } from "@/lib/constants";
+import { getLinksCount } from "@/lib/api/links";
+
+export default withUserAuth(
+ async (req: NextApiRequest, res: NextApiResponse, session: Session) => {
+ // GET /api/links/count – get the count for dub.sh links created by the user
+ if (req.method === "GET") {
+ const count = await getLinksCount({
+ req,
+ projectId: DUB_PROJECT_ID,
+ userId: session.user.id,
+ });
+ return res.status(200).json(count);
+ } else {
+ res.setHeader("Allow", ["GET"]);
+ return res
+ .status(405)
+ .json({ error: `Method ${req.method} Not Allowed` });
+ }
+ },
+);
diff --git a/pages/api/projects/[slug]/domains/index.ts b/pages/api/projects/[slug]/domains/index.ts
index cb7d41a4e9..9ceebb5e3e 100644
--- a/pages/api/projects/[slug]/domains/index.ts
+++ b/pages/api/projects/[slug]/domains/index.ts
@@ -9,7 +9,6 @@ export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse, project: ProjectProps) => {
// GET /api/projects/[slug]/domains – get all domains for a project
if (req.method === "GET") {
- const { includeLinkCount } = req.query;
const domains = await prisma.domain.findMany({
where: {
projectId: project.id,
@@ -20,13 +19,6 @@ export default withProjectAuth(
primary: true,
target: true,
type: true,
- ...(includeLinkCount && {
- _count: {
- select: {
- links: true,
- },
- },
- }),
},
});
return res.status(200).json(domains);
diff --git a/pages/api/projects/[slug]/links/count.ts b/pages/api/projects/[slug]/links/count.ts
index 0602084802..26b0c60a21 100644
--- a/pages/api/projects/[slug]/links/count.ts
+++ b/pages/api/projects/[slug]/links/count.ts
@@ -1,16 +1,15 @@
import { NextApiRequest, NextApiResponse } from "next";
import { withProjectAuth } from "@/lib/auth";
import { ProjectProps } from "@/lib/types";
+import { getLinksCount } from "@/lib/api/links";
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse, project: ProjectProps) => {
// GET /api/projects/[slug]/domains/[domain]/links/count – count the number of links for a project
if (req.method === "GET") {
- const count = await prisma.link.count({
- where: {
- projectId: project.id,
- archived: false,
- },
+ const count = await getLinksCount({
+ req,
+ projectId: project.id,
});
return res.status(200).json(count);
} else {
diff --git a/pages/api/projects/[slug]/links/index.ts b/pages/api/projects/[slug]/links/index.ts
index 837d25ce97..7a63cbb3d2 100644
--- a/pages/api/projects/[slug]/links/index.ts
+++ b/pages/api/projects/[slug]/links/index.ts
@@ -40,7 +40,6 @@ export default withProjectAuth(
if (!domain || !key || !url) {
return res.status(400).json({ error: "Missing domain or url or key" });
}
-
// Prevent the creation of recursive links
const { hostname, pathname } = new URL(url);
if (hostname === domain && pathname === `/${key}`) {
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index c69a0ce20b..31510b39f4 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -222,7 +222,7 @@ model Link {
@@index(createdAt(sort: Desc))
@@index(clicks(sort: Desc))
@@index(userId)
- @@fulltext([key, url, title, description])
+ @@fulltext([key, url])
}
model Tag {
diff --git a/yarn.lock b/yarn.lock
index 4117f49129..9f10a16360 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -6308,10 +6308,12 @@ supports-preserve-symlinks-flag@^1.0.0:
resolved "https://registry.yarnpkg.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz#6eda4bd344a3c94aea376d4cc31bc77311039e09"
integrity sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==
-swr@^1.3.0:
- version "1.3.0"
- resolved "https://registry.yarnpkg.com/swr/-/swr-1.3.0.tgz#c6531866a35b4db37b38b72c45a63171faf9f4e8"
- integrity sha512-dkghQrOl2ORX9HYrMDtPa7LTVHJjCTeZoB1dqTbnnEDlSvN8JEKpYIYurDfvbQFUUS8Cg8PceFVZNkW0KNNYPw==
+swr@^2.1.5:
+ version "2.1.5"
+ resolved "https://registry.yarnpkg.com/swr/-/swr-2.1.5.tgz#688effa719c03f6d35c66decbb0f8e79c7190399"
+ integrity sha512-/OhfZMcEpuz77KavXST5q6XE9nrOBOVcBLWjMT+oAE/kQHyE3PASrevXCtQDZ8aamntOfFkbVJp7Il9tNBQWrw==
+ dependencies:
+ use-sync-external-store "^1.2.0"
tabbable@^6.0.1:
version "6.0.1"
@@ -6573,6 +6575,11 @@ use-sidecar@^1.1.2:
detect-node-es "^1.1.0"
tslib "^2.0.0"
+use-sync-external-store@^1.2.0:
+ version "1.2.0"
+ resolved "https://registry.yarnpkg.com/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz#7dbefd6ef3fe4e767a0cf5d7287aacfb5846928a"
+ integrity sha512-eEgnFxGQ1Ife9bzYs6VLi8/4X6CObHMw9Qr9tPY43iKwsPw8xE8+EFsf/2cFZ5S3esXgpWgtSCtLNS41F+sKPA==
+
util-deprecate@^1.0.1, util-deprecate@^1.0.2, util-deprecate@~1.0.1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf"