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.

Refactor core.ts

Tim Wilsond42929602ee9
diff --git a/packages/embeds/core/src/core.ts b/packages/embeds/core/src/core.ts
index b402ebd661..f96b60a922 100644
--- a/packages/embeds/core/src/core.ts
+++ b/packages/embeds/core/src/core.ts
@@ -38,247 +38,265 @@ const CLOSE_BUTTON_STYLES = {
right: "20px",
padding: "4px",
color: "white",
+ backgroundColor: "transparent",
+ border: "none",
+ cursor: "pointer",
};
-const createIframe = (iframeUrl: string, token: string): HTMLIFrameElement => {
- const iframe = document.createElement("iframe");
+class DubWidget {
+ options: DubOptions;
+ prefix: string;
+ container: HTMLElement | null;
- iframe.src = `${iframeUrl}?token=${token}`;
- iframe.style.width = "100%";
- iframe.style.height = "100%";
- iframe.style.border = "none";
- iframe.setAttribute("credentialssupport", "");
- iframe.setAttribute("allow", "clipboard-write");
+ constructor(options: DubOptions) {
+ options.trigger = options.trigger ?? "floating-button";
+ options.buttonPlacement = options.buttonPlacement ?? "bottom-right";
- return iframe;
-};
+ this.options = options;
+ this.prefix = options.id ? `${options.id}-` : "";
-/**
- * Generates and renders all of the widget's DOM elements.
- */
-const renderWidget = (
- options: DubOptions,
- { prefix, closeWidget }: { prefix?: string; closeWidget: () => void },
-) => {
- console.debug("[Dub] Rendering widget.", options);
-
- const {
- token,
- containerStyles,
- popupStyles,
- onClose,
- onError,
- onTokenExpired,
- } = options;
-
- const existingContainer = document.getElementById(
- `${prefix}${DUB_CONTAINER_ID}`,
- );
-
- if (existingContainer) {
- document.body.removeChild(existingContainer);
- onClose?.();
- return { container: existingContainer };
- }
+ console.debug("[Dub] Initializing.", options);
+
+ const prefix = options.id ? `${options.id}-` : "";
- if (!token) {
- console.error("[Dub] A link token is required to embed the widget.");
- return { container: null };
+ this.container = this.renderWidget();
+
+ if (options.trigger === "floating-button") {
+ createFloatingButton({
+ prefix,
+ buttonStyles: options.buttonStyles,
+ buttonPlacement: options.buttonPlacement,
+ onClick: () => this.toggleWidget(),
+ });
+ }
}
- const container = document.createElement("div");
- container.id = `${prefix}${DUB_CONTAINER_ID}`;
- Object.assign(container.style, {
- ...CONTAINER_STYLES,
- ...containerStyles,
- display: "none",
- });
-
- container.addEventListener("click", (e) => {
- if (e.target === container) closeWidget();
- });
-
- const popup: HTMLElement =
- container.querySelector("#" + CSS.escape(`${prefix}${DUB_POPUP_ID}`)) ??
- document.createElement("div");
- popup.id = `${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 = `${prefix}${DUB_CLOSE_BUTTON_ID}`;
- closeButton.innerHTML = CLOSE_ICON;
- Object.assign(closeButton.style, CLOSE_BUTTON_STYLES);
- closeButton.addEventListener("click", () => closeWidget());
-
- popup.appendChild(iframe);
- popup.appendChild(closeButton);
- container.appendChild(popup);
-
- // Listen the message from the iframe
- window.addEventListener("message", (e) => {
- const { data, event } = e.data as IframeMessage;
-
- console.debug("[Dub] Iframe message", data);
-
- if (event === "ERROR") {
- onError?.(
- new EmbedError({
- code: data?.code ?? "",
- message: data?.message ?? "",
- }),
- );
+ /**
+ * Generates and renders all of the widget's DOM elements.
+ */
+ renderWidget() {
+ console.debug("[Dub] Rendering widget.");
+
+ const {
+ token,
+ containerStyles,
+ popupStyles,
+ onClose,
+ onError,
+ onTokenExpired,
+ } = this.options;
+
+ const existingContainer = document.getElementById(
+ `${this.prefix}${DUB_CONTAINER_ID}`,
+ );
+
+ if (existingContainer) {
+ document.body.removeChild(existingContainer);
+ onClose?.();
+ return existingContainer;
}
- if (data?.code === "unauthorized") {
- onTokenExpired?.();
+ if (!token) {
+ console.error("[Dub] A link token is required to embed the widget.");
+ return null;
}
- });
- document.body.appendChild(container);
+ const container = document.createElement("div");
+ container.id = `${this.prefix}${DUB_CONTAINER_ID}`;
+ Object.assign(container.style, {
+ ...CONTAINER_STYLES,
+ ...containerStyles,
+ display: "none",
+ });
- return { container };
-};
+ container.addEventListener("click", (e) => {
+ if (e.target === container) this.closeWidget();
+ });
-/**
- * Checks if the widget is open.
- */
-const isWidgetOpen = (prefix?: string) => (): boolean => {
- const container = document.getElementById(`${prefix}${DUB_CONTAINER_ID}`);
- return container?.style.display !== "none";
-};
+ 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,
+ });
-/**
- * Opens the widget.
- */
-const openWidget = (prefix?: string) => (): void => {
- const popup = document.getElementById(`${prefix}${DUB_POPUP_ID}`);
- const container = document.getElementById(`${prefix}${DUB_CONTAINER_ID}`);
- if (!popup) {
- console.error("[Dub] No popup found.");
- return;
+ 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);
+
+ // Listen the message from the iframe
+ window.addEventListener("message", (e) => {
+ const { data, event } = e.data as IframeMessage;
+
+ console.debug("[Dub] Iframe message", data);
+
+ if (event === "ERROR") {
+ onError?.(
+ new EmbedError({
+ code: data?.code ?? "",
+ message: data?.message ?? "",
+ }),
+ );
+ }
+
+ if (data?.code === "unauthorized") {
+ onTokenExpired?.();
+ }
+ });
+
+ document.body.appendChild(container);
+
+ return container;
}
- if (container) {
- container.style.display = "flex";
- container.animate(
- [
- {
- backgroundColor: "rgba(115, 115, 115, 0)",
- },
+ /**
+ * Checks if the widget is open.
+ */
+ isWidgetOpen() {
+ const container = document.getElementById(
+ `${this.prefix}${DUB_CONTAINER_ID}`,
+ );
+ return container?.style.display !== "none";
+ }
+
+ /**
+ * 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.display = "flex";
+ container.animate(
+ [
+ {
+ backgroundColor: "rgba(115, 115, 115, 0)",
+ },
+ {
+ backgroundColor: "rgba(115, 115, 115, 0.3)",
+ },
+ ],
{
- 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-out",
+ easing: "ease-in-out",
fill: "forwards",
},
);
}
- popup.getAnimations().forEach((a) => a.cancel());
- popup.animate(
- [
- { transform: "translateY(10px)", opacity: 0 },
- { transform: "translateY(0)", opacity: 1 },
- ],
- {
- duration: 250,
+ /**
+ * 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",
- },
- );
-};
+ });
-/**
- * Closes the widget.
- */
-const closeWidget = (prefix?: string) => (): void => {
- const popup = document.getElementById(`${prefix}${DUB_POPUP_ID}`);
- const container = document.getElementById(`${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(
- [
+ if (container) {
+ container.animate(
+ [
+ {
+ backgroundColor: "rgba(115, 115, 115, 0.3)",
+ },
+ {
+ backgroundColor: "rgba(115, 115, 115, 0)",
+ },
+ ],
{
- backgroundColor: "rgba(115, 115, 115, 0.3)",
+ duration: 250,
+ easing: "ease-in",
+ fill: "forwards",
},
- {
- backgroundColor: "rgba(115, 115, 115, 0)",
- },
- ],
- {
- duration: 250,
- easing: "ease-in",
- fill: "forwards",
- },
- ).onfinish = () => {
- container.style.display = "none";
- };
+ ).onfinish = () => {
+ container.style.display = "none";
+ };
+ }
}
-};
-/**
- * Toggles the widget open state.
- */
-const toggleWidget = (prefix?: string) => (): void => {
- isWidgetOpen(prefix)() ? closeWidget(prefix)() : openWidget(prefix)();
+ /**
+ * Toggles the widget open state.
+ */
+ toggleWidget() {
+ this.isWidgetOpen() ? this.closeWidget() : this.openWidget();
+ }
+
+ /**
+ * Destroys the widget, removing any remaining DOM elements.
+ */
+ destroy() {
+ document.getElementById(`${this.prefix}${DUB_CONTAINER_ID}`)?.remove();
+ document
+ .getElementById(`${this.prefix}${DUB_FLOATING_BUTTON_ID}`)
+ ?.remove();
+ }
+}
+
+const createIframe = (iframeUrl: string, token: string): HTMLIFrameElement => {
+ const iframe = document.createElement("iframe");
+
+ iframe.src = `${iframeUrl}?token=${token}`;
+ iframe.style.width = "100%";
+ iframe.style.height = "100%";
+ iframe.style.border = "none";
+ iframe.setAttribute("credentialssupport", "");
+ iframe.setAttribute("allow", "clipboard-write");
+
+ return iframe;
};
/**
* Initializes the Dub embed widget.
*/
export const init = (options: DubOptions): DubInitResult => {
- options.trigger = options.trigger ?? "floating-button";
- options.buttonPlacement = options.buttonPlacement ?? "bottom-right";
-
- console.debug("[Dub] Initializing.", options);
-
- const prefix = options.id ? `${options.id}-` : "";
-
- const { container } = renderWidget(options, {
- prefix,
- closeWidget: closeWidget(prefix),
- });
-
- if (!container) {
- return null;
- }
-
- if (options.trigger === "floating-button") {
- createFloatingButton({
- prefix,
- buttonStyles: options.buttonStyles,
- buttonPlacement: options.buttonPlacement,
- onClick: () => {
- toggleWidget(prefix)();
- },
- });
- }
+ const widget = new DubWidget(options);
return {
- openWidget: openWidget(prefix),
- closeWidget: closeWidget(prefix),
- toggleWidget: toggleWidget(prefix),
- isWidgetOpen: isWidgetOpen(prefix),
- destroy: () => {
- document.getElementById(`${prefix}${DUB_CONTAINER_ID}`)?.remove();
- document.getElementById(`${prefix}${DUB_FLOATING_BUTTON_ID}`)?.remove();
- },
+ 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),
};
};
diff --git a/packages/embeds/core/src/example/widget.html b/packages/embeds/core/src/example/widget.html
index 79e3fdd397..1d3a0ab992 100644
--- a/packages/embeds/core/src/example/widget.html
+++ b/packages/embeds/core/src/example/widget.html
@@ -5,14 +5,16 @@
<body>
<h1>Dub Referral Widget</h1>
<script>
+ let toggle = null;
document.addEventListener("DOMContentLoaded", () => {
- Dub.init({
+ const widget = Dub.init({
token: "dub_embed_",
});
+ toggle = widget.toggleWidget;
});
</script>
<!-- Custom toggle button -->
- <button onclick="window.Dub.toggleWidget()">Click Me</button>
+ <button onclick="toggle()">Click Me</button>
</body>
</html>
\ No newline at end of file