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.

Message and rich text improvements rebuild

Marcus Farrell6c0bd155b435
diff --git a/apps/web/ui/messages/message-markdown.tsx b/apps/web/ui/messages/message-markdown.tsx
index 9b9c1106ec..c8cfe9237e 100644
--- a/apps/web/ui/messages/message-markdown.tsx
+++ b/apps/web/ui/messages/message-markdown.tsx
@@ -1,3 +1,4 @@
+import { Tooltip } from "@dub/ui";
import { cn } from "@dub/utils";
import ReactMarkdown from "react-markdown";
import "react-medium-image-zoom/dist/styles.css";
@@ -22,7 +23,7 @@ export function MessageMarkdown({
"prose-h2:text-xl prose-h2:font-semibold prose-h2:mt-6 prose-h2:mb-3",
"prose-h3:text-lg prose-h3:font-semibold prose-h3:mt-4 prose-h3:mb-2",
"prose-h4:text-base prose-h4:font-semibold prose-h4:mt-3 prose-h4:mb-1",
- "prose-p:leading-5 prose-p:mb-4 prose-p:m-2.5",
+ "prose-p:leading-5 prose-p:m-0 [&_p+p]:mt-2",
"prose-a:font-medium prose-a:underline prose-a:underline-offset-2",
"prose-strong:font-semibold",
"prose-em:italic",
@@ -38,15 +39,15 @@ export function MessageMarkdown({
invert
? [
"prose-headings:text-white prose-headings:border-neutral-600",
- "prose-p:text-neutral-200",
- "prose-a:text-neutral-300 hover:prose-a:text-neutral-100",
+ "prose-p:text-white",
+ "prose-a:text-white hover:prose-a:text-white/80",
"prose-strong:text-white",
- "prose-em:text-neutral-200",
- "prose-code:text-neutral-100 prose-code:bg-neutral-800",
+ "prose-em:text-white",
+ "prose-code:text-white prose-code:bg-neutral-800",
"prose-pre:bg-neutral-800 prose-pre:border-neutral-600",
- "prose-blockquote:border-neutral-500 prose-blockquote:text-neutral-300",
- "prose-ul:text-neutral-200",
- "prose-ol:text-neutral-200",
+ "prose-blockquote:border-neutral-500 prose-blockquote:text-white",
+ "prose-ul:text-white",
+ "prose-ol:text-white",
"prose-hr:border-neutral-600",
"prose-img:border-neutral-600",
]
@@ -80,7 +81,15 @@ export function MessageMarkdown({
]}
components={{
a: ({ node, ...props }) => (
- <a {...props} target="_blank" rel="noopener noreferrer" />
+ <Tooltip
+ content={
+ <span className="text-content-default block max-w-[200px] break-all px-2.5 py-1.5 text-xs">
+ {props.href}
+ </span>
+ }
+ >
+ <a {...props} target="_blank" rel="noopener noreferrer" />
+ </Tooltip>
),
img: ({ node, ...props }) => <ZoomImage {...props} />,
p: ({ node, children, ...props }) => {
diff --git a/apps/web/ui/messages/messages-panel.tsx b/apps/web/ui/messages/messages-panel.tsx
index 58adce41b6..5eb3b19c4a 100644
--- a/apps/web/ui/messages/messages-panel.tsx
+++ b/apps/web/ui/messages/messages-panel.tsx
@@ -164,6 +164,10 @@ export function MessagesPanel({
const isFirstFromSender =
idx === 0 || !isMessageSameSender(message, messages[idx - 1]);
+ // Messages continuing a sender's group sit tighter together:
+ // trims the container's 8px gap down to 2px
+ const isGroupedWithPrevious = !isFirstFromSender && !isNewTime;
+
return (
<Fragment
key={`${new Date(message.createdAt).getTime()}-${message.senderUserId}-${message.senderPartnerId}`}
@@ -199,6 +203,7 @@ export function MessagesPanel({
showStatusIndicator={showStatusIndicator}
isNewTime={isNewTime}
isFirstFromSender={isFirstFromSender}
+ isGroupedWithPrevious={isGroupedWithPrevious}
isNew={isNew}
program={program}
/>
@@ -210,6 +215,7 @@ export function MessagesPanel({
? "origin-bottom-right flex-row-reverse"
: "origin-bottom-left",
isNew && "animate-scale-in-fade",
+ isGroupedWithPrevious && "-mt-1.5",
)}
>
{/* Avatar */}
@@ -438,6 +444,7 @@ function CampaignMessage({
showStatusIndicator,
isNewTime,
isFirstFromSender,
+ isGroupedWithPrevious,
isNew,
program,
}: {
@@ -448,6 +455,7 @@ function CampaignMessage({
showStatusIndicator: boolean;
isNewTime: boolean;
isFirstFromSender: boolean;
+ isGroupedWithPrevious: boolean;
isNew: boolean;
program?: Pick<ProgramProps, "logo" | "name"> | null;
}) {
@@ -461,6 +469,7 @@ function CampaignMessage({
? "origin-bottom-right flex-row-reverse"
: "origin-bottom-left",
isNew && "animate-scale-in-fade",
+ isGroupedWithPrevious && "-mt-1.5",
)}
>
<MessageAvatar sender={sender} program={program} message={message} />
@@ -530,7 +539,7 @@ function CampaignMessage({
<div
className={cn(
"max-w-lg overflow-hidden",
- isExpanded ? "px-2 py-2.5" : "max-h-0 px-2 py-0",
+ isExpanded ? "px-4 py-2.5" : "max-h-0 px-4 py-0",
)}
>
<MessageMarkdown invert={isMySide}>
diff --git a/packages/ui/src/rich-text-area/index.tsx b/packages/ui/src/rich-text-area/index.tsx
index 25f7619623..4de0ce77f0 100644
--- a/packages/ui/src/rich-text-area/index.tsx
+++ b/packages/ui/src/rich-text-area/index.tsx
@@ -3,6 +3,7 @@ import { EditorContent, EditorContentProps } from "@tiptap/react";
import { LoadingSpinner } from "../icons";
import { useRichTextContext } from "./rich-text-provider";
+export * from "./link-modal";
export * from "./rich-text-provider";
export * from "./rich-text-toolbar";
diff --git a/packages/ui/src/rich-text-area/link-hover-tooltip.tsx b/packages/ui/src/rich-text-area/link-hover-tooltip.tsx
new file mode 100644
index 0000000000..9dfe8dc913
--- /dev/null
+++ b/packages/ui/src/rich-text-area/link-hover-tooltip.tsx
@@ -0,0 +1,76 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { createPortal } from "react-dom";
+import { useRichTextContext } from "./rich-text-provider";
+
+/**
+ * Tooltip that shows a link's full URL when hovering it inside the editor.
+ * The editor's anchors are rendered by ProseMirror (outside React), so this
+ * tracks hover via DOM events rather than wrapping the elements.
+ */
+export function RichTextLinkHoverTooltip() {
+ const { editor, linkModalState } = useRichTextContext();
+ const [hovered, setHovered] = useState<{
+ href: string;
+ rect: DOMRect;
+ } | null>(null);
+
+ useEffect(() => {
+ if (!editor) return;
+
+ const dom = editor.view.dom as HTMLElement;
+
+ const onMouseOver = (e: MouseEvent) => {
+ const anchor =
+ e.target instanceof Element ? e.target.closest("a[href]") : null;
+
+ if (anchor && dom.contains(anchor)) {
+ setHovered({
+ href: anchor.getAttribute("href") ?? "",
+ rect: anchor.getBoundingClientRect(),
+ });
+ }
+ };
+
+ const onMouseOut = (e: MouseEvent) => {
+ const anchor =
+ e.target instanceof Element ? e.target.closest("a[href]") : null;
+ const toAnchor =
+ e.relatedTarget instanceof Element
+ ? e.relatedTarget.closest("a[href]")
+ : null;
+
+ if (anchor && anchor !== toAnchor) setHovered(null);
+ };
+
+ const clear = () => setHovered(null);
+
+ dom.addEventListener("mouseover", onMouseOver);
+ dom.addEventListener("mouseout", onMouseOut);
+ window.addEventListener("scroll", clear, true);
+
+ return () => {
+ dom.removeEventListener("mouseover", onMouseOver);
+ dom.removeEventListener("mouseout", onMouseOut);
+ window.removeEventListener("scroll", clear, true);
+ };
+ }, [editor]);
+
+ if (!hovered || linkModalState) return null;
+
+ return createPortal(
+ <div
+ className="pointer-events-none fixed z-[99] -translate-x-1/2 -translate-y-full"
+ style={{
+ left: hovered.rect.left + hovered.rect.width / 2,
+ top: hovered.rect.top - 8,
+ }}
+ >
+ <div className="animate-slide-up-fade border-border-default bg-bg-default text-content-default max-w-[200px] break-all rounded-xl border px-2.5 py-1.5 text-xs shadow-sm">
+ {hovered.href}
+ </div>
+ </div>,
+ document.body,
+ );
+}
diff --git a/packages/ui/src/rich-text-area/link-modal.tsx b/packages/ui/src/rich-text-area/link-modal.tsx
new file mode 100644
index 0000000000..94c677de29
--- /dev/null
+++ b/packages/ui/src/rich-text-area/link-modal.tsx
@@ -0,0 +1,161 @@
+"use client";
+
+import { isSafeLinkHref } from "@dub/utils";
+import { FormEvent, useState } from "react";
+import { toast } from "sonner";
+import { Button } from "../button";
+import { useMediaQuery } from "../hooks";
+import { Modal } from "../modal";
+import {
+ RichTextLinkModalState,
+ useRichTextContext,
+} from "./rich-text-provider";
+
+/**
+ * Prefixes `https://` when the value doesn't already have a usable scheme,
+ * so users can enter e.g. "dub.co" or "https://dub.co" interchangeably.
+ */
+export function normalizeLinkHref(value: string) {
+ const trimmed = value.trim();
+ if (!trimmed) return trimmed;
+ if (isSafeLinkHref(trimmed)) return trimmed;
+ if (/^(https?:\/\/|mailto:)/i.test(trimmed)) return trimmed;
+ return `https://${trimmed}`;
+}
+
+export function RichTextLinkModal() {
+ const { linkModalState } = useRichTextContext();
+
+ return linkModalState ? (
+ <RichTextLinkModalInner state={linkModalState} />
+ ) : null;
+}
+
+function RichTextLinkModalInner({ state }: { state: RichTextLinkModalState }) {
+ const { editor, setLinkModalState } = useRichTextContext();
+ const { isMobile } = useMediaQuery();
+
+ const [text, setText] = useState(state.text);
+ const [href, setHref] = useState(state.href);
+
+ const isEditing = Boolean(state.href);
+
+ const close = () => {
+ setLinkModalState(null);
+ setTimeout(() => editor?.commands.focus(), 0);
+ };
+
+ const handleSave = (e: FormEvent) => {
+ e.preventDefault();
+ if (!editor) return;
+
+ const finalHref = normalizeLinkHref(href);
+
+ if (!isSafeLinkHref(finalHref)) {
+ toast.error(
+ "Enter a full URL starting with http://, https://, or mailto: (e.g. https://dub.co).",
+ );
+ return;
+ }
+
+ editor
+ .chain()
+ .focus()
+ .insertContentAt({ from: state.from, to: state.to }, [
+ {
+ type: "text",
+ text: text.trim() || finalHref,
+ marks: [{ type: "link", attrs: { href: finalHref } }],
+ },
+ ])
+ .run();
+
+ setLinkModalState(null);
+ };
+
+ const handleDelete = () => {
+ if (!editor) return;
+
+ editor
+ .chain()
+ .focus()
+ .setTextSelection({ from: state.from, to: state.to })
+ .unsetLink()
+ .run();
+
+ setLinkModalState(null);
+ };
+
+ return (
+ <Modal showModal setShowModal={() => close()}>
+ <div className="border-b border-neutral-200 px-6 py-4">
+ <h3 className="text-lg font-medium">
+ {isEditing ? "Edit link" : "Add link"}
+ </h3>
+ </div>
+
+ <form
+ onSubmit={handleSave}
+ className="bg-neutral-50 sm:rounded-b-2xl"
+ autoComplete="off"
+ >
+ <div className="flex flex-col gap-6 px-6 py-6">
+ <label>
+ <span className="block text-sm font-medium text-neutral-700">
+ Text
+ </span>
+ <input
+ type="text"
+ value={text}
+ autoFocus={!isMobile}
+ onChange={(e) => setText(e.target.value)}
+ className="mt-2 block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
+ />
+ </label>
+
+ <label>
+ <span className="block text-sm font-medium text-neutral-700">
+ Link
+ </span>
+ <input
+ type="text"
+ value={href}
+ placeholder="https://dub.co"
+ onChange={(e) => setHref(e.target.value)}
+ onBlur={() => setHref((href) => normalizeLinkHref(href))}
+ className="mt-2 block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
+ />
+ </label>
+ </div>
+
+ <div className="flex items-center justify-between gap-2 border-t border-neutral-200 px-6 py-4">
+ {isEditing ? (
+ <Button
+ variant="outline"
+ text="Delete link"
+ onClick={handleDelete}
+ className="h-9 w-fit px-4"
+ />
+ ) : (
+ <div />
+ )}
+
+ <div className="flex items-center gap-2">
+ <Button
+ variant="secondary"
+ text="Cancel"
+ onClick={close}
+ className="h-9 w-fit px-4"
+ />
+ <Button
+ variant="primary"
+ text="Save"
+ disabled={!href.trim()}
+ className="h-9 w-fit px-4"
+ />
+ </div>
+ </div>
+ </form>
+ </Modal>
+ );
+}
diff --git a/packages/ui/src/rich-text-area/rich-text-provider.tsx b/packages/ui/src/rich-text-area/rich-text-provider.tsx
index 665f2ecf7a..8850db69bd 100644
--- a/packages/ui/src/rich-text-area/rich-text-provider.tsx
+++ b/packages/ui/src/rich-text-area/rich-text-provider.tsx
@@ -11,13 +11,17 @@ import {
PropsWithChildren,
createContext,
forwardRef,
+ useCallback,
useContext,
useEffect,
useImperativeHandle,
useMemo,
+ useRef,
useState,
} from "react";
import { configureCampaignEditorImage } from "./campaign-editor-image";
+import { RichTextLinkHoverTooltip } from "./link-hover-tooltip";
+import { RichTextLinkModal } from "./link-modal";
import { RichTextVariableInfo, suggestions } from "./variables";
export const PROSE_STYLES = {
@@ -62,6 +66,13 @@ type RichTextProviderProps = PropsWithChildren<{
editorClassName?: string;
}>;
+export type RichTextLinkModalState = {
+ from: number;
+ to: number;
+ text: string;
+ href: string;
+};
+
export const RichTextContext = createContext<
| (Pick<
RichTextProviderProps,
@@ -72,6 +83,9 @@ export const RichTextContext = createContext<
handleImageUpload:
| ((file: File, currentEditor: Editor, pos: number) => Promise<void>)
| null;
+ linkModalState: RichTextLinkModalState | null;
+ setLinkModalState: (state: RichTextLinkModalState | null) => void;
+ openLinkModal: (pos?: number) => void;
})
| null
>(null);
@@ -105,6 +119,32 @@ export const RichTextProvider = forwardRef<
) => {
const [isUploading, setIsUploading] = useState(false);
+ const [linkModalState, setLinkModalState] =
+ useState<RichTextLinkModalState | null>(null);
+
+ // Ref to avoid stale closures in editorProps handlers below
+ const editorRef = useRef<Editor | null>(null);
+
+ const openLinkModal = useCallback((pos?: number) => {
+ const editor = editorRef.current;
+ if (!editor) return;
+
+ const chain = editor.chain();
+ if (pos !== undefined) chain.setTextSelection(pos);
+ chain.run();
+
+ if (editor.isActive("link")) editor.chain().extendMarkRange("link").run();
+
+ const { from, to } = editor.state.selection;
+
+ setLinkModalState({
+ from,
+ to,
+ text: editor.state.doc.textBetween(from, to, " "),
+ href: editor.getAttributes("link").href ?? "",
+ });
+ }, []);
+
const handleImageUpload = useMemo(
() =>
uploadImage
@@ -155,6 +195,9 @@ export const RichTextProvider = forwardRef<
? [
Link.extend({
inclusive: false,
+ }).configure({
+ // Clicking a link opens the edit modal instead of the URL
+ openOnClick: false,
}),
]
: []),
@@ -270,6 +313,21 @@ export const RichTextProvider = forwardRef<
),
},
...editorProps,
+ handleClick: (view, pos, event) => {
+ if (editorProps?.handleClick?.(view, pos, event)) return true;
+
+ // Open the link edit modal when clicking a link in the editor
+ if (
+ features.includes("links") &&
+ event.target instanceof Element &&
+ event.target.closest("a[href]")
+ ) {
+ openLinkModal(pos);
+ return true;
+ }
+
+ return false;
+ },
},
content: initialValue,
contentType: markdown ? "markdown" : undefined,
@@ -277,6 +335,8 @@ export const RichTextProvider = forwardRef<
immediatelyRender: false,
});
+ editorRef.current = editor;
+
useEffect(() => {
editor?.setEditable(editable ?? true);
}, [editor, editable]);
@@ -297,9 +357,19 @@ export const RichTextProvider = forwardRef<
editor,
isUploading,
handleImageUpload,
+ linkModalState,
+ setLinkModalState,
+ openLinkModal,
}}
>
{children}
+
+ {features.includes("links") && (
+ <>
+ <RichTextLinkModal />
+ <RichTextLinkHoverTooltip />
+ </>
+ )}
</RichTextContext.Provider>
);
},
diff --git a/packages/ui/src/rich-text-area/rich-text-toolbar.tsx b/packages/ui/src/rich-text-area/rich-text-toolbar.tsx
index 53c5dcb1ab..b4b7c21798 100644
--- a/packages/ui/src/rich-text-area/rich-text-toolbar.tsx
+++ b/packages/ui/src/rich-text-area/rich-text-toolbar.tsx
@@ -140,14 +140,12 @@ export function RichTextToolbar({
}
function LinkButton() {
- const { editor, features } = useRichTextContext();
+ const { editor, features, openLinkModal } = useRichTextContext();
const imageControlsEnabled = features?.includes("imageControls");
const editorState = useEditorState({
editor,
selector: ({ editor }) => ({
- isTextSelection:
- editor?.state.selection.from !== editor?.state.selection.to,
isImageSelected: Boolean(editor?.isActive("image")),
isLinkActive: Boolean(
editor?.isActive("link") ||
@@ -158,10 +156,11 @@ function LinkButton() {
}),
});
- const canLink =
- editorState?.isTextSelection ||
- editorState?.isLinkActive ||
- (imageControlsEnabled && editorState?.isImageSelected);
+ const canLink = Boolean(
+ editor &&
+ (!editorState?.isImageSelected ||
+ (imageControlsEnabled && editorState?.isImageSelected)),
+ );
return (
<RichTextToolbarButton
@@ -207,30 +206,7 @@ function LinkButton() {
return;
}
- const previousUrl = editor.getAttributes("link").href;
-
- const url = window.prompt("Link URL", previousUrl);
-
- if (url === null) return;
-
- if (!url.trim()) {
- editor.chain().focus().extendMarkRange("link").unsetLink().run();
- return;
- }
-
- if (!isSafeLinkHref(url.trim())) {
- toast.error(
- "Enter a full URL starting with http://, https://, or mailto: (e.g. https://dub.co).",
- );
- return;
- }
-
- editor
- .chain()
- .focus()
- .extendMarkRange("link")
- .setLink({ href: url.trim() })
- .run();
+ openLinkModal();
}}
disabled={!canLink}
/>