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.

remove embed popup + updating naming for DubEmbed

Steven Tey19d00d0fa596
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/settings/program-settings.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/settings/program-settings.tsx
index 6376994a5a..47ea23d59a 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/settings/program-settings.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/settings/program-settings.tsx
@@ -133,7 +133,7 @@ function ProgramSettingsForm({ program }: { program: ProgramProps }) {
<h2 className="text-xl font-medium text-neutral-900">Program</h2>
<Button
type="button"
- text="Embed widget"
+ text="Embed"
onClick={() => setIsEmbedDocsOpen(true)}
icon={<Code className="size-4" />}
className="h-8 w-fit"
diff --git a/apps/web/app/app.dub.co/(dashboard)/account/settings/referrals/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/account/settings/referrals/page-client.tsx
index 8c5b029e24..62d78e8e35 100644
--- a/apps/web/app/app.dub.co/(dashboard)/account/settings/referrals/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/account/settings/referrals/page-client.tsx
@@ -2,7 +2,7 @@
import LayoutLoader from "@/ui/layout/layout-loader";
import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
-import { DubWidget } from "@dub/embed-react";
+import { DubEmbed } from "@dub/embed-react";
import { CursorRays, Hyperlink, InvoiceDollar, UserCheck } from "@dub/ui/icons";
import { fetcher } from "@dub/utils";
import { useSession } from "next-auth/react";
@@ -43,5 +43,5 @@ export function ReferralsPageClient() {
);
}
- return <DubWidget token={publicToken} variant="inline" />;
+ return <DubEmbed token={publicToken} />;
}
diff --git a/apps/web/app/app.dub.co/embed/activity.tsx b/apps/web/app/app.dub.co/embed/inline/activity.tsx
similarity index 100%
rename from apps/web/app/app.dub.co/embed/activity.tsx
rename to apps/web/app/app.dub.co/embed/inline/activity.tsx
diff --git a/apps/web/app/app.dub.co/embed/faq.tsx b/apps/web/app/app.dub.co/embed/inline/faq.tsx
similarity index 100%
rename from apps/web/app/app.dub.co/embed/faq.tsx
rename to apps/web/app/app.dub.co/embed/inline/faq.tsx
diff --git a/apps/web/app/app.dub.co/embed/leaderboard.tsx b/apps/web/app/app.dub.co/embed/inline/leaderboard.tsx
similarity index 100%
rename from apps/web/app/app.dub.co/embed/leaderboard.tsx
rename to apps/web/app/app.dub.co/embed/inline/leaderboard.tsx
diff --git a/apps/web/app/app.dub.co/embed/inline/page-client.tsx b/apps/web/app/app.dub.co/embed/inline/page-client.tsx
index a790c9b510..d3f83facd1 100644
--- a/apps/web/app/app.dub.co/embed/inline/page-client.tsx
+++ b/apps/web/app/app.dub.co/embed/inline/page-client.tsx
@@ -14,14 +14,14 @@ import {
import { cn, getPrettyUrl } from "@dub/utils";
import { AnimatePresence } from "framer-motion";
import { CSSProperties, useState } from "react";
-import { EmbedActivity } from "../activity";
-import { EmbedFAQ } from "../faq";
-import { EmbedLeaderboard } from "../leaderboard";
-import { EmbedPayouts } from "../payouts";
-import { EmbedQuickstart } from "../quickstart";
-import { EmbedSales } from "../sales";
import { LinkToken } from "../token";
+import { EmbedActivity } from "./activity";
+import { EmbedFAQ } from "./faq";
import { HeroBackground } from "./hero-background";
+import { EmbedLeaderboard } from "./leaderboard";
+import { EmbedPayouts } from "./payouts";
+import { EmbedQuickstart } from "./quickstart";
+import { EmbedSales } from "./sales";
export function EmbedInlinePageClient({
program,
diff --git a/apps/web/app/app.dub.co/embed/payouts.tsx b/apps/web/app/app.dub.co/embed/inline/payouts.tsx
similarity index 100%
rename from apps/web/app/app.dub.co/embed/payouts.tsx
rename to apps/web/app/app.dub.co/embed/inline/payouts.tsx
diff --git a/apps/web/app/app.dub.co/embed/quickstart.tsx b/apps/web/app/app.dub.co/embed/inline/quickstart.tsx
similarity index 100%
rename from apps/web/app/app.dub.co/embed/quickstart.tsx
rename to apps/web/app/app.dub.co/embed/inline/quickstart.tsx
diff --git a/apps/web/app/app.dub.co/embed/sales.tsx b/apps/web/app/app.dub.co/embed/inline/sales.tsx
similarity index 100%
rename from apps/web/app/app.dub.co/embed/sales.tsx
rename to apps/web/app/app.dub.co/embed/inline/sales.tsx
diff --git a/apps/web/app/app.dub.co/embed/loading.tsx b/apps/web/app/app.dub.co/embed/loading.tsx
deleted file mode 100644
index c500943e90..0000000000
--- a/apps/web/app/app.dub.co/embed/loading.tsx
+++ /dev/null
@@ -1,9 +0,0 @@
-import { LoadingSpinner } from "@dub/ui/icons";
-
-export default function EmbedLoading() {
- return (
- <div className="flex min-h-screen flex-col items-center justify-center">
- <LoadingSpinner />
- </div>
- );
-}
diff --git a/apps/web/app/app.dub.co/embed/use-iframe-visibility.ts b/apps/web/app/app.dub.co/embed/use-iframe-visibility.ts
deleted file mode 100644
index 8d46c739aa..0000000000
--- a/apps/web/app/app.dub.co/embed/use-iframe-visibility.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { useEffect, useState } from "react";
-
-export function useIframeVisibility() {
- const [isIframeVisible, setIsIframeVisible] = useState(false);
-
- useEffect(() => {
- const isInIframe = window !== window.parent;
-
- if (isInIframe) {
- setIsIframeVisible(false);
-
- const handleVisibilityChange = () => {
- const isVisible =
- document.visibilityState === "visible" && !document.hidden;
- setIsIframeVisible(isVisible);
- };
-
- const handleFocus = () => {
- if (document.visibilityState === "visible" && !document.hidden) {
- setIsIframeVisible(true);
- }
- };
-
- const handleBlur = () => {
- setIsIframeVisible(false);
- };
-
- document.addEventListener("visibilitychange", handleVisibilityChange);
- window.addEventListener("focus", handleFocus);
- window.addEventListener("blur", handleBlur);
- document.addEventListener("focus", handleFocus);
- document.addEventListener("blur", handleBlur);
-
- const observer = new IntersectionObserver(
- ([entry]) => {
- if (!entry.isIntersecting) {
- setIsIframeVisible(false);
- }
- },
- { threshold: [0] },
- );
-
- if (window.frameElement) {
- observer.observe(window.frameElement);
- }
-
- return () => {
- document.removeEventListener(
- "visibilitychange",
- handleVisibilityChange,
- );
- window.removeEventListener("focus", handleFocus);
- window.removeEventListener("blur", handleBlur);
- document.removeEventListener("focus", handleFocus);
- document.removeEventListener("blur", handleBlur);
- observer.disconnect();
- };
- } else {
- setIsIframeVisible(true);
- }
- }, []);
-
- return isIframeVisible;
-}
diff --git a/apps/web/app/app.dub.co/embed/widget/page-client.tsx b/apps/web/app/app.dub.co/embed/widget/page-client.tsx
deleted file mode 100644
index 774782399a..0000000000
--- a/apps/web/app/app.dub.co/embed/widget/page-client.tsx
+++ /dev/null
@@ -1,263 +0,0 @@
-"use client";
-
-import { Link, Program } from "@dub/prisma/client";
-import {
- AnimatedSizeContainer,
- Button,
- buttonVariants,
- ToggleGroup,
- useCopyToClipboard,
- Wordmark,
-} from "@dub/ui";
-import {
- Check2,
- Copy,
- EnvelopeArrowRight,
- GiftFill,
- LinkedIn,
- QRCode,
- Twitter,
-} from "@dub/ui/icons";
-import { cn, getPrettyUrl } from "@dub/utils";
-import { motion } from "framer-motion";
-import { CSSProperties, useState } from "react";
-import { EmbedActivity } from "../activity";
-import { EmbedSales } from "../sales";
-import { LinkToken } from "../token";
-import { useIframeVisibility } from "../use-iframe-visibility";
-
-type Tab = "invite" | "rewards";
-
-const heroAnimationDuration = 0.2;
-
-export function EmbedWidgetPageClient({
- program,
- link,
- hasPartnerProfile,
-}: {
- program: Program;
- link: Link;
- hasPartnerProfile: boolean;
-}) {
- const [copied, copyToClipboard] = useCopyToClipboard();
- const [selectedTab, setSelectedTab] = useState<Tab>("invite");
-
- const isIframeVisible = useIframeVisibility();
-
- return (
- <div
- className="flex min-h-screen flex-col"
- style={
- { "--accent-color": program.brandColor || "#171717" } as CSSProperties
- }
- >
- <div
- className={cn(
- "flex flex-col rounded-lg rounded-b-none bg-[var(--accent-color,black)]",
- )}
- >
- <AnimatedSizeContainer
- height
- transition={{ type: "easeInOut", duration: heroAnimationDuration }}
- className="flex flex-col justify-end"
- >
- <div className="flex h-full flex-col justify-end px-5 pt-5">
- <div
- className={cn(
- "mb-4 transition-opacity duration-200",
- selectedTab === "rewards" && "-mt-[3.75rem] opacity-0",
- )}
- >
- <div className="flex size-11 items-center justify-center rounded-full bg-white/20">
- <GiftFill className="size-5 shrink-0 text-white" />
- </div>
- </div>
- <h2 className="flex items-center text-base font-semibold text-white">
- <div
- className={cn(
- "transition-[margin-left,opacity] duration-200",
- selectedTab === "invite" && "-ml-10 opacity-0",
- )}
- >
- <div className="mr-2 flex size-8 items-center justify-center rounded-full bg-white/20">
- <GiftFill className="size-4 shrink-0 text-white" />
- </div>
- </div>
- Refer a friend and earn
- </h2>
- </div>
- </AnimatedSizeContainer>
- <AnimatedSizeContainer
- height
- transition={{ type: "easeInOut", duration: heroAnimationDuration }}
- >
- <div
- className={cn(
- "px-5 pb-5 opacity-100 transition-opacity duration-200",
- selectedTab === "rewards" && "h-0 opacity-0",
- )}
- >
- <p className="pt-2 text-sm text-white/80">
- Earn additional credits and cash when you refer a friend and they
- sign up for {program?.name}
- </p>
- </div>
- </AnimatedSizeContainer>
- </div>
-
- <div className="p-5">
- <ToggleGroup
- options={[
- { value: "invite", label: "Invite" },
- {
- value: "rewards",
- label: "Rewards",
- badge:
- link.sales > 0 ? (
- <div className="rounded bg-[var(--accent-color)] px-1.5 py-0.5 text-xs text-white">
- {link.sales}
- </div>
- ) : undefined,
- },
- ]}
- selected={selectedTab}
- selectAction={(option: Tab) => setSelectedTab(option)}
- className="grid grid-cols-2 border-transparent bg-neutral-100"
- optionClassName="w-full h-8 flex items-center justify-center font-medium"
- indicatorClassName="rounded-lg bg-white border border-neutral-100 shadow-sm"
- />
-
- <div className="mt-5">
- {selectedTab === "invite" && (
- <>
- <div className="flex flex-col gap-2">
- <span className="text-sm text-neutral-500">Invite link</span>
- <input
- type="text"
- readOnly
- value={getPrettyUrl(link.shortLink)}
- className="h-10 w-full rounded-md border border-neutral-300 px-3 text-center text-sm text-neutral-600 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500"
- />
-
- <Button
- icon={
- copied ? (
- <Check2 className="size-4" />
- ) : (
- <Copy className="size-4" />
- )
- }
- text={copied ? "Copied link" : "Copy link"}
- onClick={() => copyToClipboard(getPrettyUrl(link.shortLink))}
- className="enabled:border-[var(--accent-color)] enabled:bg-[var(--accent-color)] enabled:hover:bg-[var(--accent-color)]"
- />
- </div>
- <div className="mt-4 grid grid-cols-4 gap-2">
- {/* TODO: Add social sharing messages */}
- {[
- {
- title: "X",
- icon: Twitter,
- href: `https://x.com/intent/tweet?text=${encodeURIComponent(link.shortLink)}`,
- },
- {
- title: "LinkedIn",
- icon: LinkedIn,
- href: `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(link.shortLink)}`,
- },
- {
- title: "Email",
- icon: EnvelopeArrowRight,
- href: `mailto:?subject=Check out this link&body=${encodeURIComponent(link.shortLink)}`,
- },
- {
- title: "QR Code",
- icon: QRCode,
- href: `https://api.dub.co/qr?url=${link.shortLink}?qr=1`,
- },
- ].map(({ title, href, icon: Icon }) => {
- return (
- <a
- key={href}
- href={href}
- title={title}
- target="_blank"
- className="flex h-8 items-center justify-center rounded-md border border-neutral-300 text-neutral-800 transition-colors duration-75 hover:bg-neutral-50 active:bg-neutral-100"
- >
- <Icon className="size-4 text-neutral-800" />
- </a>
- );
- })}
- </div>
- </>
- )}
-
- {selectedTab === "rewards" && (
- <>
- <h2 className="text-sm font-semibold text-neutral-900">
- EmbedActivity
- </h2>
- <motion.div
- initial={{ height: 150, opacity: 0 }}
- animate={{ height: "auto", opacity: 1 }}
- transition={{
- duration: heroAnimationDuration + 0.05,
- ease: "easeInOut",
- }}
- className="overflow-clip"
- >
- <EmbedActivity
- clicks={link.clicks}
- leads={link.leads}
- sales={link.sales}
- />
- <div className="mt-4">
- <h2 className="text-sm font-semibold text-neutral-900">
- Recent sales
- </h2>
- <EmbedSales salesCount={link.sales} />
- {hasPartnerProfile ? (
- <a
- href="https://partners.dub.co/settings/payouts"
- target="_blank"
- className={cn(
- buttonVariants({ variant: "primary" }),
- "mt-3 flex h-10 items-center justify-center whitespace-nowrap rounded-lg border px-4 text-sm",
- )}
- >
- Withdraw earnings
- </a>
- ) : (
- <a
- href="https://partners.dub.co/register"
- target="_blank"
- className={cn(
- buttonVariants({ variant: "primary" }),
- "mt-3 flex h-10 items-center justify-center whitespace-nowrap rounded-lg border px-4 text-sm",
- )}
- >
- Create partner account
- </a>
- )}
- </div>
- </motion.div>
- </>
- )}
- {isIframeVisible && <LinkToken />}
- </div>
- </div>
- <div className="flex grow flex-col justify-end">
- <div className="flex items-center justify-center">
- <a
- href="https://d.to/conversions"
- target="_blank"
- className="flex items-center justify-center gap-1 rounded-lg bg-white p-2 pb-2.5 transition-colors"
- >
- <p className="text-sm text-neutral-500">Powered by</p>
- <Wordmark className="h-4" />
- </a>
- </div>
- </div>
- </div>
- );
-}
diff --git a/apps/web/app/app.dub.co/embed/widget/page.tsx b/apps/web/app/app.dub.co/embed/widget/page.tsx
deleted file mode 100644
index b2152d0804..0000000000
--- a/apps/web/app/app.dub.co/embed/widget/page.tsx
+++ /dev/null
@@ -1,20 +0,0 @@
-import { getEmbedData } from "../utils";
-import { EmbedWidgetPageClient } from "./page-client";
-
-export default async function EmbedWidgetPage({
- searchParams,
-}: {
- searchParams: { token: string };
-}) {
- const { token } = searchParams;
-
- const { link, program, hasPartnerProfile } = await getEmbedData(token);
-
- return (
- <EmbedWidgetPageClient
- program={program}
- link={link}
- hasPartnerProfile={hasPartnerProfile}
- />
- );
-}
diff --git a/apps/web/ui/partners/embed-docs-sheet.tsx b/apps/web/ui/partners/embed-docs-sheet.tsx
index 936a1bd205..77f5658d27 100644
--- a/apps/web/ui/partners/embed-docs-sheet.tsx
+++ b/apps/web/ui/partners/embed-docs-sheet.tsx
@@ -82,7 +82,7 @@ function EmbedDocsSheetContent({ setIsOpen }: EmbedDocsSheetProps) {
);
}
-const reactSnippet = `import { DubWidget } from "@dub/embed-react";
+const reactSnippet = `import { DubEmbed } from "@dub/embed-react";
const App = () => {
const [token, setToken] = useState("");
@@ -96,7 +96,7 @@ const App = () => {
createToken();
}, []);
- return <DubWidget
+ return <DubEmbed
token={token}
/>`;
diff --git a/packages/embeds/core/README.md b/packages/embeds/core/README.md
index a7176d8978..14c42c4151 100644
--- a/packages/embeds/core/README.md
+++ b/packages/embeds/core/README.md
@@ -1,6 +1,6 @@
# `@dub/embed-core`
-`@dub/embed-core` is a library that contains the core logic for embedding Dub's widget and dashboard on third-party websites.
+`@dub/embed-core` is a library that contains the core logic for embedding Dub's referral dashboard on third-party websites.
## Installation
diff --git a/packages/embeds/core/package.json b/packages/embeds/core/package.json
index a0e6bb838a..a1f4ccb6cc 100644
--- a/packages/embeds/core/package.json
+++ b/packages/embeds/core/package.json
@@ -1,6 +1,6 @@
{
"name": "@dub/embed-core",
- "description": "Vanilla JS core script that embeds Dub dashboards & widgets.",
+ "description": "Vanilla JS core script that embeds Dub's referral dashboard.",
"version": "0.0.2",
"sideEffects": false,
"main": "./dist/index.js",
diff --git a/packages/embeds/core/src/constants.ts b/packages/embeds/core/src/constants.ts
index 211b8b755b..8ca3eebe7d 100644
--- a/packages/embeds/core/src/constants.ts
+++ b/packages/embeds/core/src/constants.ts
@@ -1,5 +1,4 @@
-export const WIDGET_URL = "https://app.dub.co/embed/widget";
-export const INLINE_URL = "https://app.dub.co/embed/inline";
+export const EMBED_URL = "https://app.dub.co/embed/inline";
export const DUB_CONTAINER_ID = "dub-embed-container";
export const DUB_POPUP_ID = "dub-embed-popup";
diff --git a/packages/embeds/core/src/core.ts b/packages/embeds/core/src/core.ts
index 020b2f7c0f..a2b1800b96 100644
--- a/packages/embeds/core/src/core.ts
+++ b/packages/embeds/core/src/core.ts
@@ -1,93 +1,35 @@
-import {
- CLOSE_ICON,
- DUB_CLOSE_BUTTON_ID,
- DUB_CONTAINER_ID,
- DUB_FLOATING_BUTTON_ID,
- DUB_POPUP_ID,
- INLINE_URL,
- WIDGET_URL,
-} from "./constants";
+import { DUB_CONTAINER_ID, EMBED_URL } from "./constants";
import { EmbedError } from "./error";
-import { createFloatingButton } from "./floating-button";
import { DubInitResult, DubOptions, IframeMessage } from "./types";
-const INLINE_CONTAINER_STYLES = {
+const CONTAINER_STYLES = {
position: "relative",
maxWidth: "1024px",
height: "1000px",
margin: "0 auto",
};
-const CONTAINER_STYLES: Partial<CSSStyleDeclaration> = {
- position: "fixed",
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- inset: "0",
- padding: "16px",
- zIndex: "9998",
- backgroundColor: "rgba(115, 115, 115, 0.3)",
-};
-
-const POPUP_STYLES: Partial<CSSStyleDeclaration> = {
- width: "100%",
- height: "100%",
- maxWidth: "400px",
- maxHeight: "525px",
- backgroundColor: "white",
- borderRadius: "12px",
- boxShadow: "0px 8px 30px rgba(0, 0, 0, 0.12), 0px 2px 4px rgba(0, 0, 0, 0.1)",
- overflow: "hidden",
-};
-
-const CLOSE_BUTTON_STYLES = {
- position: "absolute",
- top: "20px",
- right: "20px",
- padding: "4px",
- color: "white",
- backgroundColor: "transparent",
- border: "none",
- cursor: "pointer",
-};
-
-class DubWidget {
+class DubEmbed {
options: DubOptions;
prefix: string;
container: HTMLElement | null;
constructor(options: DubOptions) {
- options.variant = options.variant ?? "popup";
- options.trigger = options.trigger ?? "floating-button";
- options.buttonPlacement = options.buttonPlacement ?? "bottom-right";
-
this.options = options;
this.prefix = options.id ? `${options.id}-` : "";
console.debug("[Dub] Initializing.", options);
- const prefix = options.id ? `${options.id}-` : "";
-
- this.container = this.renderWidget();
-
- if (options.variant === "popup" && options.trigger === "floating-button") {
- createFloatingButton({
- prefix,
- buttonStyles: options.buttonStyles,
- buttonPlacement: options.buttonPlacement,
- onClick: () => this.toggleWidget(),
- });
- }
+ this.container = this.renderEmbed();
}
/**
- * Generates and renders all of the widget's DOM elements.
+ * Generates and renders all of the embed's DOM elements.
*/
- renderWidget() {
- console.debug("[Dub] Rendering widget.");
+ renderEmbed() {
+ console.debug("[Dub] Rendering embed.");
- const { token, variant, root, containerStyles, popupStyles, onError } =
- this.options;
+ const { token, root, containerStyles, onError } = this.options;
const existingContainer = document.getElementById(
`${this.prefix}${DUB_CONTAINER_ID}`,
@@ -96,50 +38,19 @@ class DubWidget {
if (existingContainer) return existingContainer;
if (!token) {
- console.error("[Dub] A link token is required to embed the widget.");
+ console.error("[Dub] A link token is required to for the embed to work.");
return null;
}
const container = document.createElement("div");
container.id = `${this.prefix}${DUB_CONTAINER_ID}`;
Object.assign(container.style, {
- ...(variant === "inline"
- ? INLINE_CONTAINER_STYLES
- : { ...CONTAINER_STYLES, visibility: "hidden" }),
+ ...CONTAINER_STYLES,
...containerStyles,
});
- if (variant === "inline") {
- const iframe = createIframe(INLINE_URL, token);
- container.appendChild(iframe);
- } else {
- container.addEventListener("click", (e) => {
- if (e.target === container) this.closeWidget();
- });
-
- const popup: HTMLElement =
- container.querySelector(
- "#" + CSS.escape(`${this.prefix}${DUB_POPUP_ID}`),
- ) ?? document.createElement("div");
- popup.id = `${this.prefix}${DUB_POPUP_ID}`;
- Object.assign(popup.style, {
- ...POPUP_STYLES,
- ...popupStyles,
- });
-
- const iframe = createIframe(WIDGET_URL, token);
-
- // Close button
- const closeButton = document.createElement("button");
- closeButton.id = `${this.prefix}${DUB_CLOSE_BUTTON_ID}`;
- closeButton.innerHTML = CLOSE_ICON;
- Object.assign(closeButton.style, CLOSE_BUTTON_STYLES);
- closeButton.addEventListener("click", () => this.closeWidget());
-
- popup.appendChild(iframe);
- popup.appendChild(closeButton);
- container.appendChild(popup);
- }
+ const iframe = createIframe(EMBED_URL, token);
+ container.appendChild(iframe);
// Listen the message from the iframe
window.addEventListener("message", (e) => {
@@ -163,114 +74,10 @@ class DubWidget {
}
/**
- * Checks if the widget is open.
- */
- isWidgetOpen() {
- const container = document.getElementById(
- `${this.prefix}${DUB_CONTAINER_ID}`,
- );
- return container?.style.visibility !== "hidden";
- }
-
- /**
- * Opens the widget.
- */
- openWidget() {
- const popup = document.getElementById(`${this.prefix}${DUB_POPUP_ID}`);
- const container = document.getElementById(
- `${this.prefix}${DUB_CONTAINER_ID}`,
- );
- if (!popup) {
- console.error("[Dub] No popup found.");
- return;
- }
-
- if (container) {
- container.style.visibility = "visible";
- container.animate(
- [
- {
- backgroundColor: "rgba(115, 115, 115, 0)",
- },
- {
- backgroundColor: "rgba(115, 115, 115, 0.3)",
- },
- ],
- {
- duration: 250,
- easing: "ease-out",
- fill: "forwards",
- },
- );
- }
-
- popup.getAnimations().forEach((a) => a.cancel());
- popup.animate(
- [
- { transform: "translateY(10px)", opacity: 0 },
- { transform: "translateY(0)", opacity: 1 },
- ],
- {
- duration: 250,
- easing: "ease-in-out",
- fill: "forwards",
- },
- );
- }
-
- /**
- * Closes the widget.
- */
- closeWidget() {
- const popup = document.getElementById(`${this.prefix}${DUB_POPUP_ID}`);
- const container = document.getElementById(
- `${this.prefix}${DUB_CONTAINER_ID}`,
- );
- if (!popup) return;
-
- popup.getAnimations().forEach((a) => a.cancel());
- popup.animate([{ transform: "translateY(10px)", opacity: 0 }], {
- duration: 100,
- easing: "ease-in-out",
- fill: "forwards",
- });
-
- if (container) {
- container.animate(
- [
- {
- backgroundColor: "rgba(115, 115, 115, 0.3)",
- },
- {
- backgroundColor: "rgba(115, 115, 115, 0)",
- },
- ],
- {
- duration: 250,
- easing: "ease-in",
- fill: "forwards",
- },
- ).onfinish = () => {
- container.style.visibility = "hidden";
- };
- }
- }
-
- /**
- * Toggles the widget open state.
- */
- toggleWidget() {
- this.isWidgetOpen() ? this.closeWidget() : this.openWidget();
- }
-
- /**
- * Destroys the widget, removing any remaining DOM elements.
+ * Destroys the embed, removing any remaining DOM elements.
*/
destroy() {
document.getElementById(`${this.prefix}${DUB_CONTAINER_ID}`)?.remove();
- document
- .getElementById(`${this.prefix}${DUB_FLOATING_BUTTON_ID}`)
- ?.remove();
}
}
@@ -288,16 +95,12 @@ const createIframe = (iframeUrl: string, token: string): HTMLIFrameElement => {
};
/**
- * Initializes the Dub embed widget.
+ * Initializes the Dub embed.
*/
export const init = (options: DubOptions): DubInitResult => {
- const widget = new DubWidget(options);
+ const embed = new DubEmbed(options);
return {
- openWidget: widget.openWidget.bind(widget),
- closeWidget: widget.closeWidget.bind(widget),
- toggleWidget: widget.toggleWidget.bind(widget),
- isWidgetOpen: widget.isWidgetOpen.bind(widget),
- destroy: widget.destroy.bind(widget),
+ destroy: embed.destroy.bind(embed),
};
};
diff --git a/packages/embeds/core/src/example/inline.html b/packages/embeds/core/src/example/index.html
similarity index 64%
rename from packages/embeds/core/src/example/inline.html
rename to packages/embeds/core/src/example/index.html
index 3a9269a7b2..abbb3a470a 100644
--- a/packages/embeds/core/src/example/inline.html
+++ b/packages/embeds/core/src/example/index.html
@@ -1,19 +1,18 @@
-<html></html>
+<html>
<head>
<script type="module" src="../../dist/embed/script.js"></script>
</head>
<body>
- <h1>Dub Referral Widget</h1>
+ <h1>Dub Referral Embed</h1>
<script>
document.addEventListener("DOMContentLoaded", () => {
- const widget = Dub.init({
- variant: "inline",
+ const embed = Dub.init({
root: document.getElementById("root"),
token: "dub_embed_", // Add your token here
});
});
</script>
- <div id="root" style="border: 1px solid #aaa;"></div>
+ <div id="root" style="border: 1px solid #aaa"></div>
</body>
-</html>
\ No newline at end of file
+</html>
diff --git a/packages/embeds/core/src/example/popup.html b/packages/embeds/core/src/example/popup.html
deleted file mode 100644
index 28c5ddfc8b..0000000000
--- a/packages/embeds/core/src/example/popup.html
+++ /dev/null
@@ -1,20 +0,0 @@
-<html></html>
- <head>
- <script type="module" src="../../dist/embed/script.js"></script>
- </head>
- <body>
- <h1>Dub Referral Widget</h1>
- <script>
- let toggle = null;
- document.addEventListener("DOMContentLoaded", () => {
- const widget = Dub.init({
- token: "dub_embed_",
- });
- toggle = widget.toggleWidget;
- });
- </script>
-
- <!-- Custom toggle button -->
- <button onclick="toggle()">Click Me</button>
- </body>
-</html>
\ No newline at end of file
diff --git a/packages/embeds/core/src/floating-button.ts b/packages/embeds/core/src/floating-button.ts
deleted file mode 100644
index a0378d5934..0000000000
--- a/packages/embeds/core/src/floating-button.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-import { DUB_FLOATING_BUTTON_ID, GIFT_ICON } from "./constants";
-import { DubFloatingButtonPlacement } from "./types";
-
-const FLOATING_BUTTON_STYLES = (
- buttonPlacement: DubFloatingButtonPlacement,
-): Partial<CSSStyleDeclaration> => ({
- margin: "16px",
- backgroundColor: "#171717",
- color: "#fafafa",
- padding: "12px",
- borderRadius: "9999px",
- border: "none",
- transition: "transform 0.1s ease-in-out",
- position: "fixed",
- ...{
- "top-left": {
- top: "0",
- left: "0",
- },
- "top-right": {
- top: "0",
- right: "0",
- },
- "bottom-left": {
- bottom: "0",
- left: "0",
- },
- "bottom-right": {
- bottom: "0",
- right: "0",
- },
- }[buttonPlacement],
- zIndex: "9997",
-});
-
-export const createFloatingButton = ({
- prefix,
- buttonStyles,
- buttonPlacement,
- onClick,
-}: {
- prefix?: string;
- buttonStyles?: Record<string, any>;
- buttonPlacement: DubFloatingButtonPlacement;
- onClick: () => void;
-}): void => {
- const button = document.createElement("button");
- button.id = `${prefix}${DUB_FLOATING_BUTTON_ID}`;
- Object.assign(button.style, {
- ...FLOATING_BUTTON_STYLES(buttonPlacement),
- ...buttonStyles,
- });
-
- button.innerHTML = GIFT_ICON;
-
- button.addEventListener("click", () => onClick());
-
- // TODO: Figure out if we can use Tailwind classes for these states,
- // or at least make them easily overrideable
- button.addEventListener(
- "mouseenter",
- () => (button.style.transform = "scale(1.1)"),
- );
- button.addEventListener(
- "mouseleave",
- () => (button.style.transform = "scale(1)"),
- );
- button.addEventListener(
- "pointerdown",
- () => (button.style.transform = "scale(0.95)"),
- );
- button.addEventListener(
- "pointerup",
- () => (button.style.transform = "scale(1.1)"),
- );
-
- document.body.appendChild(button);
-};
diff --git a/packages/embeds/core/src/types.ts b/packages/embeds/core/src/types.ts
index d716b0b5f3..3dd24b5064 100644
--- a/packages/embeds/core/src/types.ts
+++ b/packages/embeds/core/src/types.ts
@@ -1,8 +1,4 @@
export type DubInitResult = {
- openWidget: () => void;
- closeWidget: () => void;
- toggleWidget: () => void;
- isWidgetOpen: () => boolean;
destroy: () => void;
} | null;
@@ -14,44 +10,16 @@ export type DubOptions = {
// The link token
token: string;
- // The variant of the widget
- variant?: "inline" | "popup";
-
- // The root element for the widget
+ // The root element for the embed
root?: HTMLElement;
- // The trigger for the popup widget
- trigger?: DubWidgetTrigger;
-
- // The ID of the widget (for multiple widgets on the same page)
- id?: string;
-
- // The widget was opened
- onOpen?: () => void;
-
- // The widget was closed
- onClose?: () => void;
-
// An error occurred in the APIs
onError?: (error: Error) => void;
- // The placement of the floating button
- buttonPlacement?: DubFloatingButtonPlacement;
-
- // The styles for the widget container
+ // The styles for the embed container
containerStyles?: Partial<CSSStyleDeclaration>;
- popupStyles?: Partial<CSSStyleDeclaration>;
- buttonStyles?: Partial<CSSStyleDeclaration>;
};
-export type DubWidgetTrigger = "floating-button" | "manual";
-
-export type DubFloatingButtonPlacement =
- | "bottom-right"
- | "bottom-left"
- | "top-right"
- | "top-left";
-
export interface IframeMessage {
originator?: "Dub";
event?: "ERROR";
diff --git a/packages/embeds/react/README.md b/packages/embeds/react/README.md
index 05a51af07e..ae368ee459 100644
--- a/packages/embeds/react/README.md
+++ b/packages/embeds/react/README.md
@@ -1,6 +1,6 @@
# `@dub/embed-react`
-`@dub/embed-react` is a library of React components that are used embed Dub's widget on third-party websites.
+`@dub/embed-react` is a library of React components that are used embed Dub's referral dashboard on third-party websites.
## Installation
diff --git a/packages/embeds/react/src/embed.tsx b/packages/embeds/react/src/embed.tsx
new file mode 100644
index 0000000000..bf321bbbf4
--- /dev/null
+++ b/packages/embeds/react/src/embed.tsx
@@ -0,0 +1,38 @@
+"use client";
+
+import { DubOptions, init } from "@dub/embed-core";
+import { HTMLProps, memo, useEffect, useId, useRef } from "react";
+
+type Options = Omit<DubOptions, "token">;
+
+type DubEmbedProps = {
+ token: DubOptions["token"];
+ options?: Options;
+} & HTMLProps<HTMLDivElement>;
+
+export const DubEmbed = memo(({ token, options, ...rest }: DubEmbedProps) => (
+ <DubInline options={{ ...options, token }} {...rest} />
+));
+
+function DubInline({
+ options,
+ ...rest
+}: { options: DubOptions } & HTMLProps<HTMLDivElement>) {
+ const id = useId();
+ const rootRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (!rootRef.current) return;
+
+ const { destroy } =
+ init({
+ id,
+ root: rootRef.current,
+ ...options,
+ }) || {};
+
+ return () => destroy?.();
+ }, [id, options]);
+
+ return <div {...rest} ref={rootRef} />;
+}
diff --git a/packages/embeds/react/src/example/widget.tsx b/packages/embeds/react/src/example/app.tsx
similarity index 68%
rename from packages/embeds/react/src/example/widget.tsx
rename to packages/embeds/react/src/example/app.tsx
index 7a11383fd4..f87af7053c 100644
--- a/packages/embeds/react/src/example/widget.tsx
+++ b/packages/embeds/react/src/example/app.tsx
@@ -1,8 +1,8 @@
import { useCallback, useEffect, useState } from "react";
import ReactDom from "react-dom";
-import { DubWidget } from "../widget";
+import { DubEmbed } from "../embed";
-const Widget = () => {
+const Embed = () => {
const [token, setToken] = useState("");
const createToken = useCallback(async () => {
@@ -15,7 +15,7 @@ const Widget = () => {
createToken();
}, []);
- return <DubWidget token={token} />;
+ return <DubEmbed token={token} />;
};
-ReactDom.render(<Widget />, document.getElementById("root"));
+ReactDom.render(<Embed />, document.getElementById("root"));
diff --git a/packages/embeds/react/src/index.ts b/packages/embeds/react/src/index.ts
index 97866ce19b..12b3c5295b 100644
--- a/packages/embeds/react/src/index.ts
+++ b/packages/embeds/react/src/index.ts
@@ -1 +1 @@
-export * from "./widget";
+export * from "./embed";
diff --git a/packages/embeds/react/src/widget.tsx b/packages/embeds/react/src/widget.tsx
deleted file mode 100644
index 71fd9f6385..0000000000
--- a/packages/embeds/react/src/widget.tsx
+++ /dev/null
@@ -1,105 +0,0 @@
-"use client";
-
-import { DubOptions, init } from "@dub/embed-core";
-import {
- Children,
- cloneElement,
- HTMLAttributes,
- HTMLProps,
- isValidElement,
- memo,
- PropsWithChildren,
- ReactNode,
- useEffect,
- useId,
- useRef,
-} from "react";
-
-type Options = Omit<DubOptions, "variant" | "token">;
-
-type DubWidgetProps = {
- token: DubOptions["token"];
- options?: Options;
-} & (
- | ({
- variant: "inline";
- } & HTMLProps<HTMLDivElement>)
- | {
- variant?: "popup";
- children?: ReactNode;
- }
-);
-
-export const DubWidget = memo(
- ({ variant = "popup", token, options, ...rest }: DubWidgetProps) => {
- return variant === "inline" ? (
- <DubInline options={{ ...options, token }} {...rest} />
- ) : (
- <DubPopup options={{ ...options, token }} {...rest} />
- );
- },
-);
-
-function DubInline({
- options,
- ...rest
-}: { options: Omit<DubOptions, "variant"> } & HTMLProps<HTMLDivElement>) {
- const id = useId();
- const rootRef = useRef<HTMLDivElement>(null);
-
- useEffect(() => {
- if (!rootRef.current) return;
-
- const { destroy } =
- init({
- id,
- variant: "inline",
- root: rootRef.current,
- ...options,
- }) || {};
-
- return () => destroy?.();
- }, [id, options]);
-
- return <div {...rest} ref={rootRef} />;
-}
-
-function DubPopup({
- children,
- options,
-}: PropsWithChildren<{ options: Omit<DubOptions, "variant"> }>) {
- const id = useId();
- const toggleWidgetRef = useRef<() => void>();
-
- useEffect(() => {
- const { destroy, toggleWidget } =
- init({
- id,
- variant: "popup",
- ...options,
- }) || {};
-
- toggleWidgetRef.current = toggleWidget;
-
- return () => destroy?.();
- }, [children, id, options]);
-
- return children ? (
- <Slot id={id} onClick={() => toggleWidgetRef.current?.()}>
- {children}
- </Slot>
- ) : null;
-}
-
-function Slot({
- children,
- ...props
-}: PropsWithChildren<HTMLAttributes<HTMLElement>>) {
- if (Children.count(children) > 1)
- throw new Error("DubWidget may only have one child");
-
- if (isValidElement(children))
- return cloneElement(children, { ...props, ...children.props });
-
- return null;
-}