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.

code improvements

Pedro Ladeira9c9bcb54600b
diff --git a/apps/web/lib/rewards/validate-tooltip-suggestion.ts b/apps/web/lib/rewards/validate-tooltip-suggestion.ts
index fbc1b67c74..13eb7a3691 100644
--- a/apps/web/lib/rewards/validate-tooltip-suggestion.ts
+++ b/apps/web/lib/rewards/validate-tooltip-suggestion.ts
@@ -78,12 +78,62 @@ export function applyTooltipSuggestion<
};
}
+export type TooltipSuggestionField = "operator" | "value";
+
+export type TooltipSuggestionPage = {
+ suggestion: TooltipSuggestion;
+ field: TooltipSuggestionField;
+};
+
+export function getTooltipSuggestionPages({
+ suggestions,
+ modifiers,
+}: {
+ suggestions: TooltipSuggestion[];
+ modifiers: Array<{
+ conditions: Array<{ operator?: ConditionOperator; value?: unknown }>;
+ }>;
+}): TooltipSuggestionPage[] {
+ const pages: TooltipSuggestionPage[] = [];
+
+ for (const suggestion of suggestions) {
+ const current =
+ modifiers[suggestion.modifierIndex]?.conditions[
+ suggestion.conditionIndex
+ ];
+
+ if (!current) continue;
+
+ if (
+ suggestionTouchesField({
+ field: "operator",
+ current,
+ suggested: suggestion.suggested,
+ })
+ ) {
+ pages.push({ suggestion, field: "operator" });
+ }
+
+ if (
+ suggestionTouchesField({
+ field: "value",
+ current,
+ suggested: suggestion.suggested,
+ })
+ ) {
+ pages.push({ suggestion, field: "value" });
+ }
+ }
+
+ return pages;
+}
+
export function suggestionTouchesField({
field,
current,
suggested,
}: {
- field: "operator" | "value";
+ field: TooltipSuggestionField;
current: { operator?: ConditionOperator; value?: unknown };
suggested: TooltipSuggestionPatch;
}): boolean {
diff --git a/apps/web/tests/rewards/validate-tooltip-suggestion.test.ts b/apps/web/tests/rewards/validate-tooltip-suggestion.test.ts
index 453eeca227..006ff5d15c 100644
--- a/apps/web/tests/rewards/validate-tooltip-suggestion.test.ts
+++ b/apps/web/tests/rewards/validate-tooltip-suggestion.test.ts
@@ -5,6 +5,7 @@ import type {
import {
applyTooltipSuggestion,
filterValidatedTooltipSuggestions,
+ getTooltipSuggestionPages,
isRewardConditionComplete,
suggestionTouchesField,
} from "@/lib/rewards/validate-tooltip-suggestion";
@@ -226,6 +227,31 @@ describe("applyTooltipSuggestion", () => {
});
});
+describe("getTooltipSuggestionPages", () => {
+ test("splits one suggestion that changes operator and value into two pages", () => {
+ const pages = getTooltipSuggestionPages({
+ modifiers: saleAmountModifiers,
+ suggestions: [
+ {
+ ...minTwentySuggestion,
+ suggested: { operator: "greater_than_or_equal", value: 25 },
+ },
+ ],
+ });
+
+ expect(pages.map((page) => page.field)).toEqual(["operator", "value"]);
+ });
+
+ test("keeps one page when only the operator changes", () => {
+ expect(
+ getTooltipSuggestionPages({
+ modifiers: saleAmountModifiers,
+ suggestions: [minTwentySuggestion],
+ }),
+ ).toHaveLength(1);
+ });
+});
+
describe("suggestionTouchesField", () => {
test("detects operator vs value changes", () => {
const current = saleAmountModifiers[0].conditions[0];
diff --git a/apps/web/ui/partners/rewards/rewards-logic.tsx b/apps/web/ui/partners/rewards/rewards-logic.tsx
index a66f843172..c3ba5620a5 100644
--- a/apps/web/ui/partners/rewards/rewards-logic.tsx
+++ b/apps/web/ui/partners/rewards/rewards-logic.tsx
@@ -65,7 +65,10 @@ import {
} from "../../shared/inline-badge-popover";
import { useAddEditRewardForm } from "./add-edit-reward-sheet";
import { RewardIconSquare } from "./reward-icon-square";
-import { SuggestedFixBadge } from "./suggested-fix-popover";
+import {
+ SuggestedFixBadge,
+ SuggestedFixPopoverHost,
+} from "./suggested-fix-popover";
import {
RewardTooltipConsistencyContext,
useRewardTooltipConsistency,
@@ -127,6 +130,7 @@ export function RewardsLogic({
return (
<RewardTooltipConsistencyContext.Provider value={consistency}>
+ <SuggestedFixPopoverHost />
<div
className={cn(
"flex flex-col gap-2",
@@ -648,6 +652,7 @@ function ConditionLogic({
) : highlightOperator && condition.operator ? (
<SuggestedFixBadge
text={CONDITION_OPERATOR_LABELS[condition.operator]}
+ field="operator"
modifierIndex={modifierIndex}
conditionIndex={conditionIndex}
/>
@@ -741,6 +746,7 @@ function ConditionLogic({
: undefined,
) ?? "Value"
}
+ field="value"
modifierIndex={modifierIndex}
conditionIndex={conditionIndex}
/>
diff --git a/apps/web/ui/partners/rewards/suggested-fix-popover.tsx b/apps/web/ui/partners/rewards/suggested-fix-popover.tsx
index 3e5d4abe51..1230f1689f 100644
--- a/apps/web/ui/partners/rewards/suggested-fix-popover.tsx
+++ b/apps/web/ui/partners/rewards/suggested-fix-popover.tsx
@@ -5,136 +5,162 @@ import { formatRewardConditionParts } from "@/lib/rewards/format-reward-conditio
import {
applyTooltipSuggestion,
getRewardConditionAttribute,
- suggestionTouchesField,
+ type TooltipSuggestionField,
} from "@/lib/rewards/validate-tooltip-suggestion";
import { RewardCondition } from "@/lib/types";
import { Button, InvoiceDollar, Popover, useMediaQuery } from "@dub/ui";
import { Sparkle3 } from "@dub/ui/icons";
import { cn } from "@dub/utils";
-import { useRef, useState, type ReactNode } from "react";
+import { type ReactNode } from "react";
import { useWatch } from "react-hook-form";
import { useAddEditRewardForm } from "./add-edit-reward-sheet";
-import { useRewardTooltipConsistencyContext } from "./use-reward-tooltip-consistency";
+import {
+ tooltipSuggestionPageKey,
+ useRewardTooltipConsistencyContext,
+} from "./use-reward-tooltip-consistency";
+
+const POPOVER_CONTENT_CLASS_NAME =
+ "w-[min(411px,calc(100vw-2rem))] overflow-hidden rounded-xl border-neutral-200 bg-white p-0 drop-shadow-none shadow-[0px_4px_6px_-2px_#0000000D,0px_10px_15px_-3px_#0000001A]";
+
+export function SuggestedFixPopoverHost() {
+ const consistency = useRewardTooltipConsistencyContext();
+
+ if (!consistency) return null;
+
+ const {
+ pages,
+ activeIndex,
+ open,
+ activeAnchorRef,
+ showPage,
+ scheduleHide,
+ cancelHide,
+ hide,
+ accept,
+ acceptAll,
+ dismiss,
+ dismissAll,
+ } = consistency;
+
+ const activePage = pages[activeIndex];
+ const isMultiple = pages.length > 1;
+
+ return (
+ <Popover
+ openPopover={open && !!activePage}
+ setOpenPopover={(next) => {
+ if (!next) hide();
+ }}
+ align="start"
+ sideOffset={8}
+ virtualAnchorRef={activeAnchorRef}
+ onOpenAutoFocus={(event) => event.preventDefault()}
+ popoverContentClassName={POPOVER_CONTENT_CLASS_NAME}
+ content={
+ activePage ? (
+ <div onMouseEnter={cancelHide} onMouseLeave={scheduleHide}>
+ <SuggestedFixContent
+ suggestion={activePage.suggestion}
+ field={activePage.field}
+ index={activeIndex}
+ total={pages.length}
+ onNext={() => showPage((activeIndex + 1) % pages.length)}
+ onDiscard={() => {
+ if (isMultiple) {
+ dismissAll();
+ } else {
+ dismiss(activePage.suggestion);
+ }
+ }}
+ onAccept={() => {
+ if (isMultiple) {
+ acceptAll();
+ } else {
+ accept(activePage.suggestion);
+ }
+ }}
+ />
+ </div>
+ ) : (
+ <div />
+ )
+ }
+ >
+ <span
+ aria-hidden
+ className="pointer-events-none absolute left-0 top-0 h-0 w-0 overflow-hidden opacity-0"
+ />
+ </Popover>
+ );
+}
export function SuggestedFixBadge({
text,
+ field,
modifierIndex,
conditionIndex,
}: {
text: string;
+ field: TooltipSuggestionField;
modifierIndex: number;
conditionIndex: number;
}) {
const consistency = useRewardTooltipConsistencyContext();
const { isMobile } = useMediaQuery();
- const [open, setOpen] = useState(false);
- const closeTimer = useRef<number | undefined>(undefined);
if (!consistency) return null;
- const {
- suggestions,
- activeIndex,
- setActiveIndex,
- accept,
- acceptAll,
- dismiss,
- dismissAll,
- } = consistency;
-
- const thisIndex = suggestions.findIndex(
- (suggestion) =>
- suggestion.modifierIndex === modifierIndex &&
- suggestion.conditionIndex === conditionIndex,
+ const thisIndex = consistency.getPageIndex(
+ modifierIndex,
+ conditionIndex,
+ field,
);
if (thisIndex === -1) return null;
- const clearClose = () => {
- if (closeTimer.current) window.clearTimeout(closeTimer.current);
- };
-
- const scheduleClose = () => {
- if (isMobile) return;
- clearClose();
- closeTimer.current = window.setTimeout(() => setOpen(false), 150);
- };
-
- const active = suggestions[activeIndex] ?? suggestions[thisIndex];
- const isMultiple = suggestions.length > 1;
+ const isOpen = consistency.open && consistency.activeIndex === thisIndex;
return (
- <Popover
- openPopover={open}
- setOpenPopover={setOpen}
- align="start"
- sideOffset={8}
- onOpenAutoFocus={(event) => event.preventDefault()}
- popoverContentClassName="w-[min(411px,calc(100vw-2rem))] overflow-hidden rounded-xl border-neutral-200 bg-white p-0 drop-shadow-none shadow-[0px_4px_6px_-2px_#0000000D,0px_10px_15px_-3px_#0000001A]"
- content={
- <div
- onMouseEnter={() => {
- if (!isMobile) {
- clearClose();
- setOpen(true);
- }
- }}
- onMouseLeave={scheduleClose}
- >
- <SuggestedFixContent
- suggestion={active}
- index={Math.max(activeIndex, 0)}
- total={suggestions.length}
- onNext={() =>
- setActiveIndex((activeIndex + 1) % suggestions.length)
- }
- onDiscard={() => {
- if (isMultiple) {
- dismissAll();
- } else {
- dismiss(active);
- }
- setOpen(false);
- }}
- onAccept={() => {
- if (isMultiple) {
- acceptAll();
- } else {
- accept(active);
- }
- setOpen(false);
- }}
- />
- </div>
+ <button
+ type="button"
+ ref={(element) =>
+ consistency.registerBadge(
+ tooltipSuggestionPageKey({ modifierIndex, conditionIndex, field }),
+ element,
+ )
}
+ onMouseEnter={() => {
+ if (!isMobile) consistency.showPage(thisIndex);
+ }}
+ onMouseLeave={() => {
+ if (!isMobile) consistency.scheduleHide();
+ }}
+ onClick={() => {
+ if (!isMobile) return;
+
+ if (isOpen) {
+ consistency.hide();
+ return;
+ }
+
+ consistency.showPage(thisIndex);
+ }}
+ className="inline-block rounded bg-[#FFFBEB] px-1.5 text-left text-sm font-semibold text-[#973C00] transition-colors"
>
- <button
- type="button"
- onMouseEnter={() => {
- if (!isMobile) {
- clearClose();
- setActiveIndex(thisIndex);
- setOpen(true);
- }
- }}
- onMouseLeave={scheduleClose}
- onClick={() => {
- if (isMobile) {
- setOpen((current) => !current);
- setActiveIndex(thisIndex);
- }
- }}
- className="inline-flex items-center gap-1 rounded bg-[#FFFBEB] px-1.5 text-left align-middle text-sm font-semibold leading-[inherit] text-[#973C00] transition-colors"
- >
- <Sparkle3 variant="fill" className="size-3 shrink-0 text-[#E17100]" />
+ <span>
+ <Sparkle3
+ variant="fill"
+ className="mr-1 inline-block size-3 align-middle text-[#E17100]"
+ />
{text}
- </button>
- </Popover>
+ </span>
+ </button>
);
}
function SuggestedFixContent({
suggestion,
+ field,
index,
total,
onNext,
@@ -142,6 +168,7 @@ function SuggestedFixContent({
onAccept,
}: {
suggestion: TooltipSuggestion;
+ field: TooltipSuggestionField;
index: number;
total: number;
onNext: () => void;
@@ -163,7 +190,12 @@ function SuggestedFixContent({
return null;
}
- const patched = applyTooltipSuggestion(current, suggestion.suggested);
+ const patched = applyTooltipSuggestion(
+ current,
+ field === "operator"
+ ? { operator: suggestion.suggested.operator }
+ : { value: suggestion.suggested.value },
+ );
const entity = patched.entity ?? current.entity;
const attribute = patched.attribute ?? current.attribute;
const operator = patched.operator ?? current.operator;
@@ -199,7 +231,7 @@ function SuggestedFixContent({
Suggested fix
</div>
{isMultiple && (
- <span className="text-xs text-neutral-500">
+ <span className="flex h-4 w-fit items-center justify-center rounded-md bg-[#EDEDED] px-1 text-[12px] font-semibold leading-4 tracking-[-0.02em] text-[#404040]">
{index + 1} of {total}
</span>
)}
@@ -213,24 +245,10 @@ function SuggestedFixContent({
<p className="min-w-0 text-sm font-medium leading-relaxed text-neutral-800">
If <PreviewChip>{entityLabel}</PreviewChip>{" "}
<PreviewChip>{attributeLabel}</PreviewChip>{" "}
- <PreviewChip
- changed={suggestionTouchesField({
- field: "operator",
- current,
- suggested: suggestion.suggested,
- })}
- >
+ <PreviewChip changed={field === "operator"}>
{operatorLabel}
</PreviewChip>{" "}
- <PreviewChip
- changed={suggestionTouchesField({
- field: "value",
- current,
- suggested: suggestion.suggested,
- })}
- >
- {valueLabel}
- </PreviewChip>
+ <PreviewChip changed={field === "value"}>{valueLabel}</PreviewChip>
</p>
</div>
diff --git a/apps/web/ui/partners/rewards/use-reward-tooltip-consistency.ts b/apps/web/ui/partners/rewards/use-reward-tooltip-consistency.ts
index fffe0f61dd..f3b2bbb71a 100644
--- a/apps/web/ui/partners/rewards/use-reward-tooltip-consistency.ts
+++ b/apps/web/ui/partners/rewards/use-reward-tooltip-consistency.ts
@@ -11,8 +11,11 @@ import type {
} from "@/lib/ai/review-reward-tooltip-schema";
import {
getRewardConditionAttribute,
+ getTooltipSuggestionPages,
isRewardConditionComplete,
stripRewardTooltipMarkdown,
+ type TooltipSuggestionField,
+ type TooltipSuggestionPage,
} from "@/lib/rewards/validate-tooltip-suggestion";
import { EventType } from "@prisma/client";
import {
@@ -23,19 +26,45 @@ import {
useMemo,
useRef,
useState,
+ type MutableRefObject,
} from "react";
const DEBOUNCE_MS = 200;
+const HIDE_MS = 300;
const reviewCache = new Map<string, TooltipSuggestion[]>();
+export function tooltipSuggestionPageKey({
+ modifierIndex,
+ conditionIndex,
+ field,
+}: {
+ modifierIndex: number;
+ conditionIndex: number;
+ field: TooltipSuggestionField;
+}) {
+ return `${modifierIndex}:${conditionIndex}:${field}`;
+}
+
type RewardTooltipConsistencyValue = {
suggestions: TooltipSuggestion[];
+ pages: TooltipSuggestionPage[];
activeIndex: number;
- setActiveIndex: (index: number) => void;
+ open: boolean;
+ activeAnchorRef: MutableRefObject<HTMLElement | null>;
+ registerBadge: (key: string, element: HTMLElement | null) => void;
+ showPage: (index: number) => void;
+ scheduleHide: () => void;
+ cancelHide: () => void;
+ hide: () => void;
getSuggestion: (
modifierIndex: number,
conditionIndex: number,
) => TooltipSuggestion | undefined;
+ getPageIndex: (
+ modifierIndex: number,
+ conditionIndex: number,
+ field: TooltipSuggestionField,
+ ) => number;
accept: (suggestion: TooltipSuggestion) => void;
acceptAll: () => void;
dismiss: (suggestion: TooltipSuggestion) => void;
@@ -74,8 +103,12 @@ export function useRewardTooltipConsistency({
}): RewardTooltipConsistencyValue {
const [suggestions, setSuggestions] = useState<TooltipSuggestion[]>([]);
const [activeIndex, setActiveIndex] = useState(0);
+ const [open, setOpen] = useState(false);
const [dismissedKeys, setDismissedKeys] = useState<string[]>([]);
const requestIdRef = useRef(0);
+ const closeTimerRef = useRef<number | undefined>(undefined);
+ const badgeRefs = useRef(new Map<string, HTMLElement>());
+ const activeAnchorRef = useRef<HTMLElement | null>(null);
const tooltip = stripRewardTooltipMarkdown(tooltipDescription ?? "");
const serializedModifiers = useMemo(
@@ -165,11 +198,80 @@ export function useRewardTooltipConsistency({
});
}, [dismissedKeys, serializedModifiers, suggestions]);
+ const pages = useMemo(
+ () =>
+ serializedModifiers
+ ? getTooltipSuggestionPages({
+ suggestions: visibleSuggestions,
+ modifiers: serializedModifiers,
+ })
+ : [],
+ [serializedModifiers, visibleSuggestions],
+ );
useEffect(() => {
- if (activeIndex >= visibleSuggestions.length) {
+ if (activeIndex >= pages.length) {
setActiveIndex(0);
}
- }, [activeIndex, visibleSuggestions.length]);
+
+ if (!pages.length && open) {
+ setOpen(false);
+ }
+ }, [activeIndex, open, pages.length]);
+
+ const cancelHide = useCallback(() => {
+ if (closeTimerRef.current) {
+ window.clearTimeout(closeTimerRef.current);
+ closeTimerRef.current = undefined;
+ }
+ }, []);
+
+ const registerBadge = useCallback(
+ (key: string, element: HTMLElement | null) => {
+ if (element) {
+ badgeRefs.current.set(key, element);
+ } else {
+ badgeRefs.current.delete(key);
+ }
+ },
+ [],
+ );
+
+ const showPage = useCallback(
+ (index: number) => {
+ cancelHide();
+
+ const page = pages[index];
+ if (page) {
+ const element = badgeRefs.current.get(
+ tooltipSuggestionPageKey({
+ modifierIndex: page.suggestion.modifierIndex,
+ conditionIndex: page.suggestion.conditionIndex,
+ field: page.field,
+ }),
+ );
+
+ if (element) {
+ activeAnchorRef.current = element;
+ }
+ }
+
+ setActiveIndex(index);
+ setOpen(true);
+ },
+ [cancelHide, pages],
+ );
+
+ const scheduleHide = useCallback(() => {
+ cancelHide();
+ closeTimerRef.current = window.setTimeout(() => {
+ setOpen(false);
+ }, HIDE_MS);
+ }, [cancelHide]);
+
+ const hide = useCallback(() => {
+ cancelHide();
+ setOpen(false);
+ }, [cancelHide]);
const getSuggestion = useCallback(
(modifierIndex: number, conditionIndex: number) =>
@@ -181,6 +283,21 @@ export function useRewardTooltipConsistency({
[visibleSuggestions],
);
+ const getPageIndex = useCallback(
+ (
+ modifierIndex: number,
+ conditionIndex: number,
+ field: TooltipSuggestionField,
+ ) =>
+ pages.findIndex(
+ (page) =>
+ page.field === field &&
+ page.suggestion.modifierIndex === modifierIndex &&
+ page.suggestion.conditionIndex === conditionIndex,
+ ),
+ [pages],
+ );
+
const dismiss = useCallback(
(suggestion: TooltipSuggestion) => {
const current =
@@ -221,24 +338,47 @@ export function useRewardTooltipConsistency({
(suggestion: TooltipSuggestion) => {
onApply?.(suggestion);
dismiss(suggestion);
+ hide();
},
- [dismiss, onApply],
+ [dismiss, hide, onApply],
);
const acceptAll = useCallback(() => {
visibleSuggestions.forEach((suggestion) => onApply?.(suggestion));
dismissAll();
- }, [dismissAll, onApply, visibleSuggestions]);
+ hide();
+ }, [dismissAll, hide, onApply, visibleSuggestions]);
+
+ const dismissAndHide = useCallback(
+ (suggestion: TooltipSuggestion) => {
+ dismiss(suggestion);
+ hide();
+ },
+ [dismiss, hide],
+ );
+
+ const dismissAllAndHide = useCallback(() => {
+ dismissAll();
+ hide();
+ }, [dismissAll, hide]);
return {
suggestions: visibleSuggestions,
+ pages,
activeIndex,
- setActiveIndex,
+ open,
+ activeAnchorRef,
+ registerBadge,
+ showPage,
+ scheduleHide,
+ cancelHide,
+ hide,
getSuggestion,
+ getPageIndex,
accept,
acceptAll,
- dismiss,
- dismissAll,
+ dismiss: dismissAndHide,
+ dismissAll: dismissAllAndHide,
};
}
diff --git a/packages/ui/src/popover.tsx b/packages/ui/src/popover.tsx
index 3194624e02..3ac77cbc3d 100644
--- a/packages/ui/src/popover.tsx
+++ b/packages/ui/src/popover.tsx
@@ -2,7 +2,12 @@
import { cn } from "@dub/utils";
import * as PopoverPrimitive from "@radix-ui/react-popover";
-import { PropsWithChildren, ReactNode, WheelEventHandler } from "react";
+import {
+ PropsWithChildren,
+ ReactNode,
+ RefObject,
+ WheelEventHandler,
+} from "react";
import { createPortal } from "react-dom";
import { Drawer } from "vaul";
import { useMediaQuery } from "./hooks";
@@ -24,6 +29,7 @@ export type PopoverProps = PropsWithChildren<{
onWheel?: WheelEventHandler;
sideOffset?: number;
anchor?: ReactNode;
+ virtualAnchorRef?: RefObject<HTMLElement | null>;
}>;
export function Popover({
@@ -44,6 +50,7 @@ export function Popover({
onWheel,
sideOffset = 8,
anchor,
+ virtualAnchorRef,
}: PopoverProps) {
const { isMobile } = useMediaQuery();
@@ -89,6 +96,15 @@ export function Popover({
<PopoverPrimitive.Anchor asChild>{anchor}</PopoverPrimitive.Anchor>,
document.body,
)}
+ {virtualAnchorRef && (
+ <PopoverPrimitive.Anchor
+ virtualRef={
+ virtualAnchorRef as unknown as RefObject<{
+ getBoundingClientRect(): DOMRect;
+ }>
+ }
+ />
+ )}
<PopoverPrimitive.Trigger className="sm:inline-flex" asChild>
{children}
</PopoverPrimitive.Trigger>