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 relative positioning

Tim Wilson1da6c547aa51
diff --git a/apps/web/ui/layout/sidebar/refer-button.tsx b/apps/web/ui/layout/sidebar/refer-button.tsx
index cb39a98854..c7704eb8f3 100644
--- a/apps/web/ui/layout/sidebar/refer-button.tsx
+++ b/apps/web/ui/layout/sidebar/refer-button.tsx
@@ -1,6 +1,7 @@
"use client";
import useWorkspace from "@/lib/swr/use-workspace";
+import { DubWidget } from "@dub/embed-react";
import { Gift } from "@dub/ui/src/icons";
import { cn } from "@dub/utils";
import { AnimatePresence, motion } from "framer-motion";
@@ -11,23 +12,31 @@ export function ReferButton() {
if (!flags || !flags.referrals) return null;
return (
- <button
- type="button"
- className={cn(
- "font-lg relative size-4 shrink-0 overflow-hidden rounded-full transition-all active:scale-90 active:bg-gray-50",
- "outline-none ring-offset-2 ring-offset-neutral-100 focus-visible:ring-2 focus-visible:ring-black/50",
- )}
+ <DubWidget
+ // TODO: Fetch token for this workspace
+ token="dub_embed_zNettp9ZaXTmdq3VM0lODQjeIfADNqM1qj2w"
+ trigger="manual"
+ placement="top-left"
+ anchorId="dub-refer-button"
>
- <AnimatePresence>
- <motion.div
- className="absolute inset-0 flex items-center justify-center font-medium text-neutral-500 hover:text-neutral-700"
- initial={{ opacity: 0, scale: 0 }}
- animate={{ opacity: 1, scale: 1 }}
- exit={{ opacity: 0, scale: 0 }}
- >
- <Gift className="size-4" />
- </motion.div>
- </AnimatePresence>
- </button>
+ <button
+ type="button"
+ className={cn(
+ "font-lg relative size-4 shrink-0 overflow-hidden rounded-full transition-all active:scale-90 active:bg-gray-50",
+ "outline-none ring-offset-2 ring-offset-neutral-100 focus-visible:ring-2 focus-visible:ring-black/50",
+ )}
+ >
+ <AnimatePresence>
+ <motion.div
+ className="absolute inset-0 flex items-center justify-center font-medium text-neutral-500 hover:text-neutral-700"
+ initial={{ opacity: 0, scale: 0 }}
+ animate={{ opacity: 1, scale: 1 }}
+ exit={{ opacity: 0, scale: 0 }}
+ >
+ <Gift className="size-4" />
+ </motion.div>
+ </AnimatePresence>
+ </button>
+ </DubWidget>
);
}
diff --git a/packages/embeds/core/package.json b/packages/embeds/core/package.json
index 5067401fce..5046c5198f 100644
--- a/packages/embeds/core/package.json
+++ b/packages/embeds/core/package.json
@@ -35,5 +35,8 @@
],
"publishConfig": {
"access": "public"
+ },
+ "dependencies": {
+ "@floating-ui/dom": "^1.6.12"
}
}
diff --git a/packages/embeds/core/src/anchor.ts b/packages/embeds/core/src/anchor.ts
new file mode 100644
index 0000000000..d9e7341f81
--- /dev/null
+++ b/packages/embeds/core/src/anchor.ts
@@ -0,0 +1,40 @@
+import { computePosition, offset, Placement, shift } from "@floating-ui/dom";
+import { DUB_CONTAINER_ID } from "./constants";
+import { DubOptions } from "./types";
+
+export function setAnchoredPosition({
+ anchorId,
+ placement,
+}: Pick<DubOptions, "anchorId" | "placement">) {
+ if (!anchorId) return;
+
+ const anchor = document.getElementById(anchorId);
+ if (!anchor) {
+ console.error(`[Dub] No anchor found with id: ${anchorId}`);
+ return;
+ }
+
+ const container = document.getElementById(DUB_CONTAINER_ID);
+ if (!container) {
+ console.error(`[Dub] No container found with id: ${DUB_CONTAINER_ID}`);
+ return;
+ }
+
+ computePosition(anchor, container, {
+ placement: {
+ "top-left": "bottom-start",
+ center: "bottom-start",
+ "bottom-left": "top-start",
+ "top-right": "bottom-end",
+ "bottom-right": "top-end",
+ }[placement ?? "bottom-right"] as Placement,
+ middleware: [shift(), offset(16)],
+ }).then(({ x, y }) => {
+ Object.assign(container.style, {
+ top: `${y}px`,
+ left: `${x}px`,
+ right: "auto",
+ bottom: "auto",
+ });
+ });
+}
diff --git a/packages/embeds/core/src/core.ts b/packages/embeds/core/src/core.ts
index 86e20af7ed..791f73b851 100644
--- a/packages/embeds/core/src/core.ts
+++ b/packages/embeds/core/src/core.ts
@@ -1,3 +1,4 @@
+import { setAnchoredPosition } from "./anchor";
import {
CLOSE_ICON,
DASHBOARD_URL,
@@ -10,9 +11,11 @@ import { EmbedError } from "./error";
import { createFloatingButton } from "./floating-button";
import { DubOptions, DubWidgetPlacement, IframeMessage } from "./types";
-const CONTAINER_STYLES = (
- placement: DubWidgetPlacement,
-): Partial<CSSStyleDeclaration> => ({
+const CONTAINER_STYLES = ({
+ placement,
+}: {
+ placement: DubWidgetPlacement;
+}): Partial<CSSStyleDeclaration> => ({
position: "fixed",
display: "flex",
...{
@@ -54,17 +57,21 @@ const CONTAINER_STYLES = (
pointerEvents: "none",
});
-const POPUP_STYLES = (
- placement: DubWidgetPlacement,
-): Partial<CSSStyleDeclaration> => ({
- width: "calc(100% - 32px)",
+const POPUP_STYLES = ({
+ placement,
+ anchor,
+}: {
+ placement: DubWidgetPlacement;
+ anchor: boolean;
+}): Partial<CSSStyleDeclaration> => ({
+ width: anchor ? "100%" : "calc(100% - 32px)",
height: "100dvh",
maxHeight: "500px",
backgroundColor: "white",
borderRadius: "12px",
border: "1px solid #E5E5E5",
boxShadow: "0px 4px 20px 0px #0000000D",
- margin: "16px",
+ margin: anchor ? undefined : "16px",
overflow: "hidden",
...{
"bottom-right": { transformOrigin: "bottom right" },
@@ -99,12 +106,14 @@ const createIframe = (iframeUrl: string, token: string): HTMLIFrameElement => {
return iframe;
};
+type RenderDashboardResult = { container: HTMLElement | null };
+
const renderDashboard = (
options: Pick<
DubOptions,
"token" | "containerStyles" | "onError" | "onTokenExpired"
>,
-): HTMLElement | null => {
+): RenderDashboardResult => {
console.debug("[Dub] Rendering dashboard.", options);
const { token, containerStyles, onError, onTokenExpired } = options;
@@ -113,12 +122,12 @@ const renderDashboard = (
if (existingContainer) {
document.body.removeChild(existingContainer);
- return existingContainer;
+ return { container: existingContainer };
}
if (!token) {
console.error("[Dub] A link token is required to embed the widget.");
- return null;
+ return { container: null };
}
const container = document.createElement("div");
@@ -153,10 +162,15 @@ const renderDashboard = (
document.body.appendChild(container);
- return container;
+ return { container };
+};
+
+type RenderWidgetResult = {
+ container: HTMLElement | null;
+ updatePosition?: () => void;
};
-const renderWidget = (options: DubOptions): HTMLElement | null => {
+const renderWidget = (options: DubOptions): RenderWidgetResult => {
console.debug("[Dub] Rendering widget.", options);
const {
@@ -164,6 +178,7 @@ const renderWidget = (options: DubOptions): HTMLElement | null => {
placement,
containerStyles,
popupStyles,
+ anchorId,
onOpen,
onClose,
onError,
@@ -175,18 +190,20 @@ const renderWidget = (options: DubOptions): HTMLElement | null => {
if (existingContainer) {
document.body.removeChild(existingContainer);
onClose?.();
- return existingContainer;
+ return { container: existingContainer };
}
if (!token) {
console.error("[Dub] A link token is required to embed the widget.");
- return null;
+ return { container: null };
}
const container = document.createElement("div");
container.id = DUB_CONTAINER_ID;
Object.assign(container.style, {
- ...CONTAINER_STYLES(placement ?? "bottom-right"),
+ ...CONTAINER_STYLES({
+ placement: placement ?? "bottom-right",
+ }),
...containerStyles,
});
@@ -195,7 +212,10 @@ const renderWidget = (options: DubOptions): HTMLElement | null => {
document.createElement("div");
popup.id = DUB_POPUP_ID;
Object.assign(popup.style, {
- ...POPUP_STYLES(placement ?? "bottom-right"),
+ ...POPUP_STYLES({
+ placement: placement ?? "bottom-right",
+ anchor: !!anchorId,
+ }),
...popupStyles,
display: "none",
});
@@ -235,9 +255,17 @@ const renderWidget = (options: DubOptions): HTMLElement | null => {
document.body.appendChild(container);
+ let updatePosition: (() => void) | undefined;
+
+ if (anchorId) {
+ updatePosition = () => setAnchoredPosition({ anchorId, placement });
+ updatePosition();
+ window.addEventListener("resize", updatePosition);
+ }
+
onOpen?.();
- return container;
+ return { container, updatePosition };
};
export const openWidget = (): void => {
@@ -297,26 +325,35 @@ export const init = (options: DubOptions) => {
console.debug("[Dub] Initializing.", options);
- const container =
+ const renderResult: RenderDashboardResult | RenderWidgetResult =
options.type === "dashboard"
? renderDashboard(options)
: renderWidget(options);
- if (!container) {
- return;
+ if (!renderResult.container) {
+ return { destroy: () => {} };
}
if (options.trigger === "floating-button")
createFloatingButton({
- container,
+ container: renderResult.container,
buttonStyles: options.buttonStyles,
placement: options.placement,
onClick: () => {
toggleWidget();
},
});
-};
-export const destroy = (): void => {
- document.querySelectorAll(`#${DUB_CONTAINER_ID}`).forEach((c) => c.remove());
+ return {
+ ...renderResult,
+ destroy: () => {
+ document
+ .querySelectorAll(`#${DUB_CONTAINER_ID}`)
+ .forEach((c) => c.remove());
+ if ("updatePosition" in renderResult && renderResult.updatePosition)
+ window.removeEventListener("resize", renderResult.updatePosition);
+ },
+ };
};
+
+export const destroy = (): void => {};
diff --git a/packages/embeds/core/src/types.ts b/packages/embeds/core/src/types.ts
index 5bbb815193..1707bcfa8c 100644
--- a/packages/embeds/core/src/types.ts
+++ b/packages/embeds/core/src/types.ts
@@ -7,7 +7,7 @@ export interface DubEmbed {
destroy: () => void;
}
-export interface DubOptions {
+export type DubOptions = {
// The link token
token: string;
@@ -32,11 +32,14 @@ export interface DubOptions {
// The placement of the widget
placement?: DubWidgetPlacement;
+ // The ID of the anchor element
+ anchorId?: string;
+
// The styles for the widget container
containerStyles?: Partial<CSSStyleDeclaration>;
popupStyles?: Partial<CSSStyleDeclaration>;
buttonStyles?: Partial<CSSStyleDeclaration>;
-}
+};
export type DubWidgetTrigger = "floating-button" | "manual";
diff --git a/packages/embeds/react/src/widget.tsx b/packages/embeds/react/src/widget.tsx
index 7e7531feb0..ede213a65a 100644
--- a/packages/embeds/react/src/widget.tsx
+++ b/packages/embeds/react/src/widget.tsx
@@ -1,17 +1,48 @@
"use client";
-import { destroy, DubOptions, init } from "@dub/embed-core";
-import { useEffect } from "react";
+import { DubOptions, init, toggleWidget } from "@dub/embed-core";
+import {
+ Children,
+ cloneElement,
+ HTMLAttributes,
+ isValidElement,
+ memo,
+ PropsWithChildren,
+ useEffect,
+ useId,
+} from "react";
-export const DubWidget = (options: Omit<DubOptions, "type">) => {
- useEffect(() => {
- init({
- ...options,
- type: "widget",
- });
+export const DubWidget = memo(
+ ({ children, ...options }: PropsWithChildren<Omit<DubOptions, "type">>) => {
+ const id = useId();
- return () => destroy();
- }, [options]);
+ useEffect(() => {
+ const { destroy } = init({
+ ...options,
+ type: "widget",
+ anchorId: children ? id : undefined,
+ });
+
+ return () => destroy();
+ }, [children, id, options]);
+
+ return children ? (
+ <Slot id={id} onClick={() => toggleWidget()}>
+ {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;
-};
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index f96d2c032f..10dc39b223 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -490,6 +490,10 @@ importers:
version: 5.6.2
packages/embeds/core:
+ dependencies:
+ '@floating-ui/dom':
+ specifier: ^1.6.12
+ version: 1.6.12
devDependencies:
'@types/js-cookie':
specifier: ^3.0.6
@@ -4259,14 +4263,14 @@ packages:
/@floating-ui/[email protected]:
resolution: {integrity: sha512-8GrTWmoFhm5BsMZOTHeGD2/0FLKLQQHvO/ZmQga4tKempYRLz8aqJGqXVuQgisnMObq2YZ2SgkwctN1LOOxcqA==}
dependencies:
- '@floating-ui/utils': 0.2.5
+ '@floating-ui/utils': 0.2.8
dev: false
- /@floating-ui/[email protected]:
- resolution: {integrity: sha512-kx62rP19VZ767Q653wsP1XZCGIirkE09E0QUGNYTM/ttbbQHqcGPdSfWFxUyyNLc/W6aoJRBajOSXhP6GXjC0Q==}
+ /@floating-ui/[email protected]:
+ resolution: {integrity: sha512-NP83c0HjokcGVEMeoStg317VD9W7eDlGK7457dMBANbKA6GJZdc7rjujdgqzTaz93jkGgc5P/jeWbaCHnMNc+w==}
dependencies:
'@floating-ui/core': 1.6.5
- '@floating-ui/utils': 0.2.5
+ '@floating-ui/utils': 0.2.8
dev: false
@@ -4275,7 +4279,7 @@ packages:
react: '>=16.8.0'
react-dom: '>=16.8.0'
dependencies:
- '@floating-ui/dom': 1.6.8
+ '@floating-ui/dom': 1.6.12
react: 18.2.0
react-dom: 18.2.0([email protected])
dev: false
@@ -4286,7 +4290,7 @@ packages:
react: '>=16.8.0'
react-dom: '>=16.8.0'
dependencies:
- '@floating-ui/dom': 1.6.8
+ '@floating-ui/dom': 1.6.12
react: 18.2.0
react-dom: 18.2.0([email protected])
dev: false
@@ -4308,6 +4312,10 @@ packages:
resolution: {integrity: sha512-sTcG+QZ6fdEUObICavU+aB3Mp8HY4n14wYHdxK4fXjPmv3PXZZeY5RaguJmGyeH/CJQhX3fqKUtS4qc1LoHwhQ==}
dev: false
+ /@floating-ui/[email protected]:
+ resolution: {integrity: sha512-kym7SodPp8/wloecOpcmSnWJsK7M0E5Wg8UcFA+uO4B9s5d0ywXOEro/8HM9x0rW+TljRzul/14UYz3TleT3ig==}
+ dev: false
+
/@formatjs/[email protected]:
resolution: {integrity: sha512-rRqXOqdFmk7RYvj4khklyqzcfQl9vEL/usogncBHRZfZBDOwMGuSRNFl02fu5KGHXdbinju+YXyuR+Nk8xlr/g==}
dependencies: