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.

WIP embed

Tim Wilson612767201acd
diff --git a/packages/embeds/react/example/index.html b/packages/embeds/react/example/index.html
index c6781149fe..b27b1c3cef 100644
--- a/packages/embeds/react/example/index.html
+++ b/packages/embeds/react/example/index.html
@@ -12,21 +12,13 @@
</head>
<body>
<!-- Via JavaScript API -->
- <!-- <script>
+ <script>
document.addEventListener("DOMContentLoaded", () => {
- Dub.open({
+ Dub.init({
token: "dub_embed_MrRaGiUA3MkbdjTWJFHMYZrEaBR8KX355R0y",
-
- onOpen: () => {
- console.log("Widget opened");
- },
-
- onClose: () => {
- console.log("Widget closed");
- },
});
});
- </script> -->
+ </script>
<!-- Via Button using data attributes -->
<!-- <button data-dub-token="dub_embed_MrRaGiUA3MkbdjTWJFHMYZrEaBR8KX355R0y">
diff --git a/packages/embeds/react/src/embed.ts b/packages/embeds/react/src/embed.ts
index b166d9f974..eeb5ac667e 100644
--- a/packages/embeds/react/src/embed.ts
+++ b/packages/embeds/react/src/embed.ts
@@ -1,3 +1,4 @@
+import { createFloatingButton } from "./floating-button";
import { DubEmbed, Options } from "./types";
declare global {
@@ -8,26 +9,32 @@ declare global {
window.Dub = (window.Dub || {}) as DubEmbed;
-const buttonStyles: Partial<CSSStyleDeclaration> = {
+const containerStyles: Partial<CSSStyleDeclaration> = {
position: "fixed",
- bottom: "20px",
- right: "20px",
- zIndex: "9999",
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "flex-end",
+ bottom: "0",
+ right: "0",
+ width: "400px",
+ zIndex: "9998",
+ pointerEvents: "none",
};
-const containerStyles: Partial<CSSStyleDeclaration> = {
- width: "450px",
- height: "600px",
- boxShadow: "0 0 20px rgba(0,0,0,0.1)",
- borderRadius: "10px",
+const popupStyles: Partial<CSSStyleDeclaration> = {
+ width: "100%",
+ height: "100dvh",
+ maxHeight: "500px",
+ backgroundColor: "white",
+ borderRadius: "12px",
+ border: "1px solid #E5E5E5",
+ margin: "16px",
overflow: "hidden",
- position: "fixed",
- bottom: "80px",
- right: "20px",
- zIndex: "9998",
+ transformOrigin: "bottom right",
+ pointerEvents: "auto",
};
-const widgetUrl = "http://localhost:8888/embed/widget";
+const WIDGET_URL = "http://localhost:8888/embed/widget";
const createIframe = (iframeUrl: string, token: string): HTMLIFrameElement => {
const iframe = document.createElement("iframe");
@@ -41,108 +48,144 @@ const createIframe = (iframeUrl: string, token: string): HTMLIFrameElement => {
return iframe;
};
+const DUB_CONTAINER_ID = "dub-embed-container";
+const DUB_POPUP_ID = "dub-embed-popup";
+
const renderWidget = (
options: Pick<Options, "token" | "onOpen" | "onClose">,
-): void => {
- const containerId = "dub-widget-container";
+): HTMLElement | null => {
const { token, onOpen, onClose } = options;
- const existingContainer = document.getElementById(containerId);
+ const existingContainer = document.getElementById(DUB_CONTAINER_ID);
if (existingContainer) {
document.body.removeChild(existingContainer);
onClose?.();
- return;
+ return existingContainer;
}
if (!token) {
console.error("[Dub] A link token is required to embed the widget.");
- return;
+ return null;
}
const container = document.createElement("div");
- container.id = containerId;
+ container.id = DUB_CONTAINER_ID;
Object.assign(container.style, containerStyles);
- const iframe = createIframe(widgetUrl, token);
+ const popup: HTMLElement =
+ container.querySelector(`#${DUB_POPUP_ID}`) ??
+ document.createElement("div");
+ popup.id = DUB_POPUP_ID;
+ Object.assign(popup.style, { ...popupStyles, display: "none" });
+
+ const iframe = createIframe(WIDGET_URL, token);
+
+ popup.appendChild(iframe);
+ container.appendChild(popup);
- container.appendChild(iframe);
document.body.appendChild(container);
- onOpen?.();
-};
+ // onOpen?.();
-// Open the widget via JavaScript API
-window.Dub.open = (options: Options) => {
- renderWidget(options);
+ return container;
};
// Initialize when an external button is clicked
-const addButtonListener = (): void => {
- const button = document.querySelector(
- "[data-dub-token]",
- ) as HTMLElement | null;
+// const addButtonListener = (): void => {
+// const button = document.querySelector(
+// "[data-dub-token]",
+// ) as HTMLElement | null;
+
+// if (!button) {
+// console.error("[Dub] No button found with data-dub-token.");
+// return;
+// }
- if (!button) {
- console.error("[Dub] No button found with data-dub-token.");
+// button.addEventListener("click", () => {
+// const token = button.getAttribute("data-dub-token");
+
+// if (!token) {
+// console.error("[Dub] A link token is required to embed the widget.");
+// return;
+// }
+
+// renderWidget({ token });
+// });
+// };
+
+let isWidgetOpen = false;
+
+const openWidget = (): void => {
+ const popup = document.getElementById(DUB_POPUP_ID);
+ if (!popup) {
+ console.error("[Dub] No popup found.");
return;
}
- button.addEventListener("click", () => {
- const token = button.getAttribute("data-dub-token");
+ popup.getAnimations().forEach((a) => a.cancel());
+ popup.style.display = "block";
+ popup.animate(
+ [
+ { transform: "scale(0.8)", opacity: 0 },
+ { transform: "scale(1)", opacity: 1 },
+ ],
+ {
+ duration: 100,
+ easing: "ease-in-out",
+ fill: "forwards",
+ },
+ );
+
+ isWidgetOpen = window.Dub.isWidgetOpen = true;
+};
- if (!token) {
- console.error("[Dub] A link token is required to embed the widget.");
- return;
- }
+const closeWidget = (): void => {
+ const popup = document.getElementById(DUB_POPUP_ID);
+ if (!popup) return;
- renderWidget({ token });
+ popup.getAnimations().forEach((a) => a.cancel());
+ const animation = popup.animate([{ opacity: 0, transform: "scale(0.8)" }], {
+ duration: 100,
+ easing: "ease-in-out",
+ fill: "forwards",
});
+
+ animation.onfinish = () => {
+ if (popup && !isWidgetOpen) popup.style.display = "none";
+ };
+
+ isWidgetOpen = window.Dub.isWidgetOpen = false;
};
// Initialize when DOM is ready
-const init = () => {
+const init = (options: Options) => {
console.debug("[Dub] Initializing");
- setTimeout(addButtonListener, 100);
-};
-if (document.readyState === "loading") {
- document.addEventListener("DOMContentLoaded", init);
-} else {
- init();
-}
-
-// Initialize when Dub floating button is clicked
-// const createFloatingButton = (): void => {
-// const button = document.createElement("div");
-// Object.assign(button.style, buttonStyles);
-
-// button.innerHTML = `
-// <button>
-// <span>Click Me</span>
-// </button>
-// `;
-
-// button.addEventListener("click", () => {
-// const token = button.getAttribute("data-dub-token");
+ const container = renderWidget(options);
+ if (!container) return;
-// if (!token) {
-// console.error("[Dub] A link token is required to embed the widget.");
-// return;
-// }
+ createFloatingButton({
+ container,
+ onClick: () => {
+ isWidgetOpen ? closeWidget() : openWidget();
+ },
+ });
+};
-// renderWidget({ token });
-// });
+const destroy = (): void => {
+ document.querySelectorAll(`#${DUB_CONTAINER_ID}`).forEach((c) => c.remove());
+};
-// document.body.appendChild(button);
-// };
+window.Dub.init = init;
+window.Dub.destroy = destroy;
+window.Dub.openWidget = openWidget;
+window.Dub.closeWidget = closeWidget;
// TODO:
// - Add a loading state
-// - Add a close button
+// - Add a close button icon
// - Inline embed (dashboard)
-// - Floating button + widget
-// - Open on a button click
// - Reuse addEventListener logic
-// export {};
+export { destroy, init };
diff --git a/packages/embeds/react/src/floating-button.ts b/packages/embeds/react/src/floating-button.ts
new file mode 100644
index 0000000000..c799635a8b
--- /dev/null
+++ b/packages/embeds/react/src/floating-button.ts
@@ -0,0 +1,67 @@
+const DUB_FLOATING_BUTTON_ID = "dub-floating-button";
+
+const FLOATING_BUTTON_STYLES: Partial<CSSStyleDeclaration> = {
+ margin: "0 16px 16px 0",
+ backgroundColor: "#171717",
+ color: "#fafafa",
+ padding: "12px",
+ borderRadius: "9999px",
+ border: "none",
+ transition: "transform 0.1s ease-in-out",
+ pointerEvents: "auto",
+};
+
+export const createFloatingButton = ({
+ container,
+ buttonStyles,
+ onClick,
+}: {
+ container: HTMLElement;
+ buttonStyles?: Record<string, any>;
+ onClick: () => void;
+}): void => {
+ const button = document.createElement("button");
+ button.id = DUB_FLOATING_BUTTON_ID;
+ Object.assign(button.style, {
+ ...FLOATING_BUTTON_STYLES,
+ ...buttonStyles,
+ });
+
+ button.innerHTML = giftIcon;
+
+ 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)"),
+ );
+
+ container.appendChild(button);
+};
+
+const giftIcon =
+ `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18">` +
+ `<g fill="currentColor">` +
+ `<path d="M3,9.5v4.75c0,1.517,1.233,2.75,2.75,2.75h2.5v-7.5H3Z" />` +
+ `<path d="M9.75,9.5v7.5h2.5c1.517,0,2.75-1.233,2.75-2.75v-4.75h-5.25Z" />` +
+ `<path d="M15.25,4.5h-.462c.135-.307,.212-.644,.212-1,0-1.378-1.121-2.5-2.5-2.5-1.761,` +
+ `0-2.864,1.231-3.5,2.339-.636-1.107-1.739-2.339-3.5-2.339-1.379,0-2.5,1.122-2.5,2.5,0,` +
+ `.356,.077,.693,.212,1h-.462c-.965,0-1.75,.776-1.75,1.75s.785,1.75,1.75,1.75H15.25c.965,0` +
+ `,1.75-.782,1.75-1.75s-.785-1.75-1.75-1.75Zm-2.75-2c.552,0,1,.449,1,1s-.448,1-1,1h-2.419c.405` +
+ `-.86,1.176-2,2.419-2ZM4.5,3.5c0-.551,.448-1,1-1,1.234,0,2.007,1.14,2.415,2h-2.415c-.552,0-1-.449-1-1Z" />` +
+ `</g>` +
+ `</svg>`;
diff --git a/packages/embeds/react/src/types.ts b/packages/embeds/react/src/types.ts
index 027dcd7e1b..607c009c51 100644
--- a/packages/embeds/react/src/types.ts
+++ b/packages/embeds/react/src/types.ts
@@ -4,8 +4,13 @@ export interface DubEmbedOptions {
}
export interface DubEmbed {
- // Open the widget
- open: (options: Options) => void;
+ init: (options: Options) => void;
+
+ isWidgetOpen: boolean;
+ openWidget: () => void;
+ closeWidget: () => void;
+
+ destroy: () => void;
}
export interface Options {
diff --git a/packages/embeds/react/src/widget.tsx b/packages/embeds/react/src/widget.tsx
index 38fd8779a4..f05627f817 100644
--- a/packages/embeds/react/src/widget.tsx
+++ b/packages/embeds/react/src/widget.tsx
@@ -1,7 +1,9 @@
+"use client";
+
import { APP_DOMAIN } from "@dub/utils";
import { useEffect } from "react";
+import { destroy, init } from "./embed";
import { DubEmbedOptions } from "./types";
-import { iframeStyles } from "./utils";
export const DubWidget = ({ token, onTokenExpired }: DubEmbedOptions) => {
// Listen for messages from the iframe
@@ -22,13 +24,17 @@ export const DubWidget = ({ token, onTokenExpired }: DubEmbedOptions) => {
return () => window.removeEventListener("message", handleMessage);
}, [onTokenExpired]);
+ useEffect(() => {
+ init({ token });
+
+ return () => destroy();
+ }, []);
+
// If no link token is provided
if (!token) {
console.error("[Dub] A link token is required to embed the dashboard.");
return null;
}
- const widgetUrl = `${APP_DOMAIN}/embed/widget?token=${token}`;
-
- return <iframe src={widgetUrl} style={iframeStyles} />;
+ return null;
};