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.

Add "Share dashboard" modal

Tim Wilson21301da089ab
diff --git a/apps/web/ui/analytics/share-button.tsx b/apps/web/ui/analytics/share-button.tsx
new file mode 100644
index 0000000000..4acef12f6f
--- /dev/null
+++ b/apps/web/ui/analytics/share-button.tsx
@@ -0,0 +1,29 @@
+import { Button, ReferredVia } from "@dub/ui";
+import { memo, useContext } from "react";
+import { useShareDashboardModal } from "../modals/share-dashboard-modal";
+import { AnalyticsContext } from "./analytics-provider";
+
+export function ShareButton() {
+ const { domain, key } = useContext(AnalyticsContext);
+
+ return domain && key ? <ShareButtonInner domain={domain} _key={key} /> : null;
+}
+
+const ShareButtonInner = memo(
+ ({ domain, _key }: { domain: string; _key: string }) => {
+ const { ShareDashboardModal, setShowShareDashboardModal } =
+ useShareDashboardModal({ domain, _key });
+ return (
+ <>
+ <ShareDashboardModal />
+ <Button
+ variant="secondary"
+ onClick={() => setShowShareDashboardModal(true)}
+ icon={<ReferredVia className="size-4" />}
+ text="Share"
+ className="animate-fade-in w-fit"
+ />
+ </>
+ );
+ },
+);
diff --git a/apps/web/ui/analytics/share-popover.tsx b/apps/web/ui/analytics/share-popover.tsx
deleted file mode 100644
index bcbd35dbf5..0000000000
--- a/apps/web/ui/analytics/share-popover.tsx
+++ /dev/null
@@ -1,166 +0,0 @@
-import useWorkspace from "@/lib/swr/use-workspace";
-import {
- AnimatedSizeContainer,
- Button,
- Copy,
- Popover,
- ReferredVia,
- Tick,
-} from "@dub/ui";
-import { APP_DOMAIN, fetcher, getPrettyUrl } from "@dub/utils";
-import { useContext, useState } from "react";
-import { toast } from "sonner";
-import useSWR from "swr";
-import { AnalyticsContext } from "./analytics-provider";
-
-export default function SharePopover() {
- const { id: workspaceId } = useWorkspace();
- const [removing, setRemoving] = useState(false);
- const [openSharePopover, setopenSharePopoverPopover] = useState(false);
-
- const { queryString } = useContext(AnalyticsContext) as {
- queryString: string;
- };
-
- const { data, mutate, isLoading } = useSWR<{ id: string }>(
- `/api/analytics/share?${queryString}`,
- fetcher,
- );
-
- const [isCreating, setIsCreating] = useState(false);
- const [copied, setCopied] = useState(false);
-
- const handleCreate = async () => {
- setIsCreating(true);
- const res = await fetch(`/api/analytics/share?${queryString}`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- });
- if (!res.ok) {
- toast.error("Failed to create shared dashboard");
- return;
- }
- if (res.status === 200) {
- const data = await res.json();
- await mutate();
- toast.success(
- "Successfully created shared dashboard! Copied link to clipboard.",
- );
- navigator.clipboard.writeText(`${APP_DOMAIN}/share/${data.id}`);
- }
- setIsCreating(false);
- };
-
- const handleRemove = async () => {
- if (!data) {
- return;
- }
-
- if (
- !confirm(
- "Are you sure you want to remove the shared dashboard? Your existing dashboard link will break and you'll have to create a new one.",
- )
- ) {
- return;
- }
-
- setRemoving(true);
-
- const res = await fetch(
- `/api/analytics/share/${data.id}?workspaceId=${workspaceId}`,
- {
- method: "DELETE",
- },
- );
-
- if (!res.ok) {
- toast.error("Failed to remove shared dashboard.");
- return;
- }
-
- await mutate();
- toast.success("Removed shared dashboard.");
- setRemoving(false);
- };
-
- if (isLoading) {
- return null;
- }
-
- return (
- <Popover
- content={
- <AnimatedSizeContainer height>
- <div className="grid w-full gap-2 p-4 text-sm md:max-w-xs">
- <p className="font-semibold text-gray-800">
- Create a shared dashboard
- </p>
- <p className="text-gray-500">
- Share this link's analytics with anyone via a shared dashboard –
- no signup required.
- </p>
-
- {data ? (
- <>
- <div className="divide-x-200 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-3">
- <p className="whitespace-nowrap text-gray-400">
- {getPrettyUrl(`${APP_DOMAIN}/share/${data.id}`)}
- </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(
- `${APP_DOMAIN}/share/${data.id}`,
- );
- 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 className="mt-1 flex">
- <Button
- className="h-8 w-fit"
- text="Remove dashboard"
- variant="secondary"
- onClick={handleRemove}
- loading={removing}
- />
- </div>
- </>
- ) : (
- <Button
- text="Create dashboard"
- className="h-8"
- onClick={handleCreate}
- loading={isCreating}
- />
- )}
- </div>
- </AnimatedSizeContainer>
- }
- align="end"
- openPopover={openSharePopover}
- setOpenPopover={setopenSharePopoverPopover}
- >
- <Button
- variant="secondary"
- onClick={() => setopenSharePopoverPopover(!openSharePopover)}
- icon={<ReferredVia className="h-4 w-4" />}
- text="Share"
- className="w-fit"
- />
- </Popover>
- );
-}
diff --git a/apps/web/ui/analytics/toggle.tsx b/apps/web/ui/analytics/toggle.tsx
index 6bc5969991..dc92fab113 100644
--- a/apps/web/ui/analytics/toggle.tsx
+++ b/apps/web/ui/analytics/toggle.tsx
@@ -74,7 +74,7 @@ import ContinentIcon from "./continent-icon";
import DeviceIcon from "./device-icon";
import EventsOptions from "./events/events-options";
import RefererIcon from "./referer-icon";
-import SharePopover from "./share-popover";
+import { ShareButton } from "./share-button";
import { useAnalyticsFilterOption } from "./utils";
export default function Toggle({
@@ -776,7 +776,7 @@ export default function Toggle({
<div className="flex grow justify-end gap-2">
{page === "analytics" && (
<>
- {domain && key && <SharePopover />}
+ {domain && key && <ShareButton />}
<AnalyticsOptions />
</>
)}
diff --git a/apps/web/ui/modals/share-dashboard-modal.tsx b/apps/web/ui/modals/share-dashboard-modal.tsx
new file mode 100644
index 0000000000..6a6827a63c
--- /dev/null
+++ b/apps/web/ui/modals/share-dashboard-modal.tsx
@@ -0,0 +1,291 @@
+import useWorkspace from "@/lib/swr/use-workspace";
+import { LinkProps } from "@/lib/types";
+import {
+ AnimatedSizeContainer,
+ Copy,
+ LinkLogo,
+ Modal,
+ Switch,
+ Tick,
+} from "@dub/ui";
+import { ArrowTurnRight2, Globe, LoadingSpinner } from "@dub/ui/src/icons";
+import {
+ APP_DOMAIN,
+ fetcher,
+ getApexDomain,
+ getPrettyUrl,
+ linkConstructor,
+} from "@dub/utils";
+import { useCallback, useMemo, useState } from "react";
+import { toast } from "sonner";
+import useSWR from "swr";
+
+interface ShareDashboardModalProps {
+ showModal: boolean;
+ setShowModal: (showModal: boolean) => void;
+ domain: string;
+ _key: string;
+}
+
+function ShareDashboardModal(props: ShareDashboardModalProps) {
+ return (
+ <Modal {...props}>
+ <ShareDashboardModalInner {...props} />
+ </Modal>
+ );
+}
+
+function ShareDashboardModalInner({
+ domain,
+ _key: key,
+}: ShareDashboardModalProps) {
+ const { id: workspaceId } = useWorkspace();
+ const [isRemoving, setIsRemoving] = useState(false);
+
+ const { data: link, error: linkError } = useSWR<LinkProps>(
+ workspaceId && domain && key
+ ? `/api/links/info?${new URLSearchParams({ workspaceId, domain, key }).toString()}`
+ : undefined,
+ );
+
+ const { data, mutate } = useSWR<{ id: string }>(
+ workspaceId
+ ? `/api/analytics/share?${new URLSearchParams({ workspaceId, domain, key }).toString()}`
+ : undefined,
+ fetcher,
+ {
+ onSuccess: (data) => setChecked(Boolean(data)),
+ },
+ );
+
+ const [isCreating, setIsCreating] = useState(false);
+ const [copied, setCopied] = useState(false);
+
+ const handleCreate = async () => {
+ if (!workspaceId) return;
+
+ setChecked(true);
+ setIsCreating(true);
+ const res = await fetch(
+ `/api/analytics/share?${new URLSearchParams({ workspaceId, domain, key }).toString()}`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ },
+ );
+ if (!res.ok) {
+ toast.error("Failed to create shared dashboard");
+ setChecked(false);
+ return;
+ }
+ if (res.status === 200) {
+ const data = await res.json();
+ await mutate();
+ toast.success(
+ "Successfully created shared dashboard! Copied link to clipboard.",
+ );
+ navigator.clipboard.writeText(`${APP_DOMAIN}/share/${data.id}`);
+ }
+ setIsCreating(false);
+ };
+
+ const handleRemove = async () => {
+ if (!data) {
+ return;
+ }
+
+ if (
+ !confirm(
+ "Are you sure you want to remove the shared dashboard? Your existing dashboard link will break and you'll have to create a new one.",
+ )
+ ) {
+ return;
+ }
+
+ setChecked(false);
+ setIsRemoving(true);
+
+ const res = await fetch(
+ `/api/analytics/share/${data.id}?workspaceId=${workspaceId}`,
+ {
+ method: "DELETE",
+ },
+ );
+
+ if (!res.ok) {
+ toast.error("Failed to remove shared dashboard.");
+ setChecked(true);
+ return;
+ }
+
+ await mutate();
+ toast.success("Removed shared dashboard.");
+ setIsRemoving(false);
+ };
+
+ const [checked, setChecked] = useState(data !== undefined);
+
+ return (
+ <>
+ <h3 className="border-b border-gray-200 px-4 py-4 text-lg font-medium sm:px-6">
+ Share dashboard
+ </h3>
+ <div className="px-6 pb-6 pt-4">
+ <LinkCard link={link} isError={Boolean(linkError)} />
+ <AnimatedSizeContainer
+ height
+ transition={{ duration: 0.2, ease: "easeInOut" }}
+ >
+ {data !== undefined ? (
+ <>
+ <label className="flex items-center justify-between gap-2 pt-6">
+ <span className="flex items-center gap-2 text-sm text-gray-600">
+ <Globe className="size-4" />
+ Enable public sharing
+ </span>
+ <Switch
+ checked={checked}
+ fn={(checked) => (checked ? handleCreate() : handleRemove())}
+ disabled={isRemoving || isCreating}
+ />
+ </label>
+ {checked &&
+ (data ? (
+ <div className="pt-6 text-sm">
+ <div className="divide-x-200 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-3">
+ <p className="whitespace-nowrap text-gray-400">
+ {getPrettyUrl(`${APP_DOMAIN}/share/${data.id}`)}
+ </p>
+ </div>
+ <button
+ className="flex h-8 items-center gap-2 whitespace-nowrap border-l bg-white px-3 hover:bg-gray-50 active:bg-gray-100"
+ onClick={() => {
+ navigator.clipboard.writeText(
+ `${APP_DOMAIN}/share/${data.id}`,
+ );
+ 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" />
+ )}
+ Copy link
+ </button>
+ </div>
+ </div>
+ ) : (
+ <div className="flex w-full justify-center pt-6">
+ <LoadingSpinner className="size-4" />
+ </div>
+ ))}
+ </>
+ ) : (
+ <div className="flex w-full items-center justify-center pt-6">
+ <LoadingSpinner className="size-4" />
+ </div>
+ )}
+ </AnimatedSizeContainer>
+ </div>
+ </>
+ );
+}
+
+function LinkCard({
+ link,
+ isError,
+}: {
+ link: LinkProps | undefined;
+ isError: boolean;
+}) {
+ return (
+ <div className="flex items-center gap-3 rounded-lg border border-neutral-300 bg-white p-3">
+ {isError ? (
+ <span className="text-sm text-gray-400">Failed to load link</span>
+ ) : link === undefined ? (
+ <>
+ <div className="m-px size-9 animate-pulse rounded-full bg-gray-200" />
+ <div className="flex flex-col gap-2">
+ <div className="h-5 w-24 max-w-full animate-pulse rounded-md bg-gray-200" />
+ <div className="h-4 w-32 max-w-full animate-pulse rounded-md bg-gray-200" />
+ </div>
+ </>
+ ) : (
+ <>
+ <div className="relative flex shrink-0 items-center justify-center rounded-full border border-gray-200">
+ {/* Background gradient + white border */}
+ <div className="absolute inset-0 rounded-full border border-white bg-gradient-to-t from-gray-100" />
+ <div className="shrink-0 p-2">
+ <LinkLogo
+ apexDomain={link ? getApexDomain(link?.url) : ""}
+ className="size-5 sm:size-5"
+ imageProps={{
+ loading: "lazy",
+ }}
+ />
+ </div>
+ </div>
+ <div className="flex flex-col text-sm">
+ {link && (
+ <span className="truncate font-semibold leading-6 text-gray-800">
+ {linkConstructor({
+ domain: link.domain,
+ key: link.key,
+ pretty: true,
+ })}
+ </span>
+ )}
+ <div className="flex min-w-0 items-center gap-1">
+ <ArrowTurnRight2 className="h-3 w-3 shrink-0 text-gray-400" />
+ {link?.url ? (
+ <a
+ href={link.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ title={link.url}
+ className="truncate text-gray-500 transition-colors hover:text-gray-700 hover:underline hover:underline-offset-2"
+ >
+ {getPrettyUrl(link.url)}
+ </a>
+ ) : (
+ <span className="truncate text-gray-400">
+ No URL configured
+ </span>
+ )}
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+ );
+}
+
+export function useShareDashboardModal(
+ props: Pick<ShareDashboardModalProps, "domain" | "_key">,
+) {
+ const [showShareDashboardModal, setShowShareDashboardModal] = useState(false);
+
+ const ShareDashboardModalCallback = useCallback(() => {
+ return (
+ <ShareDashboardModal
+ showModal={showShareDashboardModal}
+ setShowModal={setShowShareDashboardModal}
+ {...props}
+ />
+ );
+ }, [showShareDashboardModal, setShowShareDashboardModal, props]);
+
+ return useMemo(
+ () => ({
+ setShowShareDashboardModal,
+ ShareDashboardModal: ShareDashboardModalCallback,
+ }),
+ [setShowShareDashboardModal, ShareDashboardModalCallback],
+ );
+}