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.

Image link and alt controls to campaign email editor (#4073)

Pedro Ladeiraa3d91bd92cc6
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor.tsx
index e4c8b50732..7779e4245a 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor.tsx
@@ -9,6 +9,7 @@ import { PageContentWithSidePanel } from "@/ui/layout/page-content/page-content-
import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
import {
ChevronRight,
+ DEFAULT_RICH_TEXT_FEATURES,
Lock,
PaperPlane,
RichTextArea,
@@ -509,6 +510,7 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
ref={editorRef}
editorClassName="-m-2 min-h-[200px] p-2"
style="relaxed"
+ features={[...DEFAULT_RICH_TEXT_FEATURES, "imageControls"]}
initialValue={field.value}
onChange={(editor) => field.onChange(editor.getJSON())}
variables={[...EMAIL_TEMPLATE_VARIABLES]}
diff --git a/apps/web/lib/api/workflows/render-campaign-email-html.ts b/apps/web/lib/api/workflows/render-campaign-email-html.ts
index c70b0d00b6..12df90302f 100644
--- a/apps/web/lib/api/workflows/render-campaign-email-html.ts
+++ b/apps/web/lib/api/workflows/render-campaign-email-html.ts
@@ -1,6 +1,6 @@
+import { configureCampaignEmailImage } from "@/lib/tiptap/campaign-email-image";
import { EmailTemplateVariables, TiptapNode } from "@/lib/types";
import { EMAIL_TEMPLATE_VARIABLES } from "@/lib/zod/schemas/campaigns";
-import Image from "@tiptap/extension-image";
import Mention from "@tiptap/extension-mention";
import { generateHTML } from "@tiptap/html/server";
import StarterKit from "@tiptap/starter-kit";
@@ -20,7 +20,7 @@ export function renderCampaignEmailHTML({
levels: [1, 2],
},
}),
- Image.configure({
+ configureCampaignEmailImage({
HTMLAttributes: {
style: "max-width: 100%; height: auto; margin: 12px auto;",
},
diff --git a/apps/web/lib/tiptap/campaign-email-image.ts b/apps/web/lib/tiptap/campaign-email-image.ts
new file mode 100644
index 0000000000..5b12c7aee5
--- /dev/null
+++ b/apps/web/lib/tiptap/campaign-email-image.ts
@@ -0,0 +1,43 @@
+import { isSafeLinkHref } from "@dub/utils";
+import Image, { type ImageOptions } from "@tiptap/extension-image";
+
+const CampaignEmailImageExtension = Image.extend({
+ addAttributes() {
+ return {
+ ...this.parent?.(),
+ href: {
+ default: null,
+ renderHTML: () => ({}),
+ },
+ };
+ },
+
+ renderHTML({ HTMLAttributes, node }) {
+ const href = isSafeLinkHref(node.attrs.href) ? node.attrs.href : null;
+ const img: [string, Record<string, unknown>] = [
+ "img",
+ {
+ ...this.options.HTMLAttributes,
+ ...HTMLAttributes,
+ },
+ ];
+
+ if (href) {
+ return [
+ "a",
+ {
+ href,
+ target: "_blank",
+ rel: "noopener noreferrer nofollow",
+ },
+ img,
+ ];
+ }
+
+ return img;
+ },
+});
+
+export function configureCampaignEmailImage(options: Partial<ImageOptions>) {
+ return CampaignEmailImageExtension.configure(options);
+}
diff --git a/packages/ui/src/rich-text-area/campaign-editor-image.ts b/packages/ui/src/rich-text-area/campaign-editor-image.ts
new file mode 100644
index 0000000000..186cfb0394
--- /dev/null
+++ b/packages/ui/src/rich-text-area/campaign-editor-image.ts
@@ -0,0 +1,138 @@
+"use client";
+
+import { isSafeLinkHref } from "@dub/utils";
+import Image, { type ImageOptions } from "@tiptap/extension-image";
+import { Plugin, PluginKey } from "@tiptap/pm/state";
+import { ReactNodeViewRenderer } from "@tiptap/react";
+import { ImageAltNodeView } from "./image-alt-node-view";
+
+export type ConfigureCampaignEditorImageOptions = Partial<ImageOptions> & {
+ imageAltControls?: boolean;
+};
+
+const CampaignEditorImageExtension = Image.extend({
+ addOptions() {
+ return {
+ ...this.parent?.(),
+ imageAltControls: false,
+ } as ImageOptions;
+ },
+
+ addNodeView() {
+ const { imageAltControls } = this
+ .options as ConfigureCampaignEditorImageOptions;
+
+ if (!imageAltControls) {
+ return null;
+ }
+
+ return ReactNodeViewRenderer(ImageAltNodeView);
+ },
+
+ addAttributes() {
+ return {
+ ...this.parent?.(),
+ href: {
+ default: null,
+ parseHTML: (element) => {
+ const anchor = element.closest("a");
+ const href = anchor?.getAttribute("href");
+ return isSafeLinkHref(href) ? href : null;
+ },
+ renderHTML: () => ({}),
+ },
+ };
+ },
+
+ parseHTML() {
+ return [
+ {
+ tag: this.options.allowBase64
+ ? "img[src]"
+ : 'img[src]:not([src^="data:"])',
+ getAttrs: (node) => {
+ if (!(node instanceof HTMLElement)) {
+ return false;
+ }
+
+ const anchor = node.closest("a");
+ const href = anchor?.getAttribute("href");
+
+ return {
+ src: node.getAttribute("src"),
+ alt: node.getAttribute("alt"),
+ title: node.getAttribute("title"),
+ width: node.getAttribute("width"),
+ height: node.getAttribute("height"),
+ href: isSafeLinkHref(href) ? href : null,
+ };
+ },
+ },
+ ];
+ },
+
+ renderHTML({ HTMLAttributes, node }) {
+ const href = isSafeLinkHref(node.attrs.href) ? node.attrs.href : null;
+
+ return [
+ "img",
+ {
+ ...this.options.HTMLAttributes,
+ ...HTMLAttributes,
+ ...(href ? { "data-linked-image": "" } : {}),
+ },
+ ];
+ },
+
+ addProseMirrorPlugins() {
+ return [
+ ...(this.parent?.() ?? []),
+ new Plugin({
+ key: new PluginKey("campaignEditorImageLinkClick"),
+ props: {
+ handleDOMEvents: {
+ mousedown: (view, event) => {
+ if (!view.editable || !(event instanceof MouseEvent)) {
+ return false;
+ }
+
+ if (!event.metaKey && !event.ctrlKey) {
+ return false;
+ }
+
+ const target = event.target;
+ if (!(target instanceof Element)) {
+ return false;
+ }
+
+ const img = target.closest("img[data-linked-image]");
+ if (!img || !view.dom.contains(img)) {
+ return false;
+ }
+
+ const pos = view.posAtDOM(img, 0);
+ const node = view.state.doc.nodeAt(pos);
+ const href = node?.attrs.href;
+
+ if (isSafeLinkHref(href)) {
+ event.preventDefault();
+ window.open(href, "_blank", "noopener,noreferrer");
+ return true;
+ }
+
+ return false;
+ },
+ },
+ },
+ }),
+ ];
+ },
+});
+
+export function configureCampaignEditorImage(
+ options: ConfigureCampaignEditorImageOptions,
+) {
+ return CampaignEditorImageExtension.configure(
+ options as Partial<ImageOptions>,
+ );
+}
diff --git a/packages/ui/src/rich-text-area/image-alt-node-view.tsx b/packages/ui/src/rich-text-area/image-alt-node-view.tsx
new file mode 100644
index 0000000000..878193782d
--- /dev/null
+++ b/packages/ui/src/rich-text-area/image-alt-node-view.tsx
@@ -0,0 +1,136 @@
+"use client";
+
+import { cn } from "@dub/utils";
+import type { ImageOptions } from "@tiptap/extension-image";
+import { NodeViewWrapper, ReactNodeViewProps } from "@tiptap/react";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { Button } from "../button";
+import { Input } from "../input";
+import { Popover } from "../popover";
+
+export function ImageAltNodeView({
+ node,
+ editor,
+ updateAttributes,
+ extension,
+ selected,
+}: ReactNodeViewProps) {
+ const [open, setOpen] = useState(false);
+ const [altText, setAltText] = useState(node.attrs.alt ?? "");
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ const htmlAttributes = (extension.options as Partial<ImageOptions>)
+ .HTMLAttributes;
+
+ const hasAlt = Boolean(node.attrs.alt?.trim());
+ const isEditable = editor.isEditable;
+
+ useEffect(() => {
+ setAltText(node.attrs.alt ?? "");
+ }, [node.attrs.alt]);
+
+ useEffect(() => {
+ if (!isEditable) {
+ setOpen(false);
+ }
+ }, [isEditable]);
+
+ const saveAlt = useCallback(
+ (value: string) => {
+ if (!editor.isEditable) {
+ return;
+ }
+
+ const trimmed = value.trim();
+ updateAttributes({ alt: trimmed || null });
+ },
+ [editor, updateAttributes],
+ );
+
+ const stopEvent = (event: React.SyntheticEvent) => {
+ event.preventDefault();
+ event.stopPropagation();
+ };
+
+ return (
+ <NodeViewWrapper
+ as="div"
+ className="mx-auto block w-fit max-w-full leading-none [&.ProseMirror-selectednode]:outline-none"
+ >
+ <div
+ className={cn(
+ "group relative w-fit max-w-full rounded-lg",
+ selected && "ring-2 ring-blue-500 ring-offset-2",
+ )}
+ >
+ <img
+ src={node.attrs.src}
+ alt={node.attrs.alt || ""}
+ title={node.attrs.title ?? undefined}
+ draggable
+ data-drag-handle
+ {...(node.attrs.href ? { "data-linked-image": "" } : {})}
+ className={cn(htmlAttributes?.class, "block")}
+ />
+
+ {isEditable && (
+ <div
+ className={cn(
+ "absolute bottom-2 right-2 z-10 transition-opacity duration-150",
+ hasAlt || open
+ ? "opacity-100"
+ : "pointer-events-none opacity-0 group-hover:pointer-events-auto group-hover:opacity-100",
+ )}
+ contentEditable={false}
+ >
+ <Popover
+ openPopover={open}
+ setOpenPopover={setOpen}
+ align="end"
+ side="bottom"
+ sideOffset={6}
+ forceDropdown
+ onOpenAutoFocus={(event) => {
+ event.preventDefault();
+ inputRef.current?.focus();
+ }}
+ content={
+ <div className="w-72 p-3">
+ <p className="text-content-subtle mb-1 text-xs leading-relaxed">
+ Add alt text to describe this image. This makes your email
+ more accessible and could increase your delivery rates.
+ </p>
+
+ <Input
+ ref={inputRef}
+ type="text"
+ value={altText}
+ placeholder="Alt text"
+ onChange={(event) => setAltText(event.target.value)}
+ onBlur={() => saveAlt(altText)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ saveAlt(altText);
+ setOpen(false);
+ }
+ }}
+ className="max-w-none"
+ />
+ </div>
+ }
+ >
+ <Button
+ type="button"
+ variant="secondary"
+ text="Alt"
+ className="h-7 w-auto px-2.5 text-xs"
+ onMouseDown={stopEvent}
+ />
+ </Popover>
+ </div>
+ )}
+ </div>
+ </NodeViewWrapper>
+ );
+}
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 6a8ae65b20..575f6dd82e 100644
--- a/packages/ui/src/rich-text-area/rich-text-provider.tsx
+++ b/packages/ui/src/rich-text-area/rich-text-provider.tsx
@@ -17,6 +17,7 @@ import {
useMemo,
useState,
} from "react";
+import { configureCampaignEditorImage } from "./campaign-editor-image";
import { suggestions } from "./variables";
export const PROSE_STYLES = {
@@ -36,10 +37,18 @@ const FEATURES = [
"strike",
] as const;
+export const DEFAULT_RICH_TEXT_FEATURES = FEATURES;
+
+const OPTIONAL_FEATURES = ["imageControls"] as const;
+
+export type RichTextFeature =
+ | (typeof FEATURES)[number]
+ | (typeof OPTIONAL_FEATURES)[number];
+
type RichTextProviderProps = PropsWithChildren<{
placeholder?: string;
initialValue?: any;
- features?: (typeof FEATURES)[number][];
+ features?: RichTextFeature[];
markdown?: boolean;
style?: keyof typeof PROSE_STYLES;
onChange?: (editor: Editor) => void;
@@ -157,12 +166,24 @@ export const RichTextProvider = forwardRef<
// Images
...(features.includes("images") && handleImageUpload
? [
- Image.configure({
- inline: false,
- HTMLAttributes: {
- class: "rounded-lg max-w-full h-auto",
- },
- }),
+ ...(features.includes("imageControls")
+ ? [
+ configureCampaignEditorImage({
+ inline: false,
+ imageAltControls: true,
+ HTMLAttributes: {
+ class: "rounded-lg max-w-full h-auto",
+ },
+ }),
+ ]
+ : [
+ Image.configure({
+ inline: false,
+ HTMLAttributes: {
+ class: "rounded-lg max-w-full h-auto",
+ },
+ }),
+ ]),
FileHandler.configure({
allowedMimeTypes: [
"image/png",
@@ -242,6 +263,7 @@ export const RichTextProvider = forwardRef<
"prose prose-sm prose-neutral",
PROSE_STYLES[style],
"[&_.ProseMirror-selectednode]:outline [&_.ProseMirror-selectednode]:outline-2 [&_.ProseMirror-selectednode]:outline-blue-500 [&_.ProseMirror-selectednode]:outline-offset-2",
+ "[&_.ProseMirror-selectednode:has(img)]:outline-none",
editorClassName,
),
},
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 6ebc9c74b9..53c5dcb1ab 100644
--- a/packages/ui/src/rich-text-area/rich-text-toolbar.tsx
+++ b/packages/ui/src/rich-text-area/rich-text-toolbar.tsx
@@ -1,6 +1,7 @@
-import { cn } from "@dub/utils";
+import { cn, isSafeLinkHref } from "@dub/utils";
import { useEditorState } from "@tiptap/react";
import { ReactNode, forwardRef, useRef } from "react";
+import { toast } from "sonner";
import {
AtSign,
Heading1,
@@ -139,38 +140,99 @@ export function RichTextToolbar({
}
function LinkButton() {
- const { editor } = useRichTextContext();
+ const { editor, features } = useRichTextContext();
+ const imageControlsEnabled = features?.includes("imageControls");
const editorState = useEditorState({
editor,
selector: ({ editor }) => ({
- isSelection: editor?.state.selection.from !== editor?.state.selection.to,
+ isTextSelection:
+ editor?.state.selection.from !== editor?.state.selection.to,
+ isImageSelected: Boolean(editor?.isActive("image")),
+ isLinkActive: Boolean(
+ editor?.isActive("link") ||
+ (imageControlsEnabled &&
+ editor?.isActive("image") &&
+ editor.getAttributes("image").href),
+ ),
}),
});
+ const canLink =
+ editorState?.isTextSelection ||
+ editorState?.isLinkActive ||
+ (imageControlsEnabled && editorState?.isImageSelected);
+
return (
<RichTextToolbarButton
icon={Hyperlink}
label="Link"
+ isActive={editorState?.isLinkActive}
onClick={() => {
if (!editor) return;
+
+ const isImageSelected = editor.isActive("image");
+
+ if (isImageSelected && imageControlsEnabled) {
+ const previousUrl = editor.getAttributes("image").href ?? "";
+ const url = window.prompt("Link URL", previousUrl);
+ const nodePos = editor.state.selection.from;
+
+ if (url === null) return;
+
+ if (!url.trim()) {
+ editor
+ .chain()
+ .focus()
+ .updateAttributes("image", { href: null })
+ .setNodeSelection(nodePos)
+ .run();
+ return;
+ }
+
+ if (!isSafeLinkHref(url.trim())) {
+ toast.error(
+ "Enter a full URL starting with http://, https://, or mailto: (e.g. https://dub.co).",
+ );
+ editor.chain().focus().setNodeSelection(nodePos).run();
+ return;
+ }
+
+ editor
+ .chain()
+ .focus()
+ .updateAttributes("image", { href: url.trim() })
+ .setNodeSelection(nodePos)
+ .run();
+ return;
+ }
+
const previousUrl = editor.getAttributes("link").href;
const url = window.prompt("Link URL", previousUrl);
- if (!url?.trim()) {
+ 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 })
+ .setLink({ href: url.trim() })
.run();
}}
- disabled={!editorState?.isSelection}
+ disabled={!canLink}
/>
);
}
diff --git a/packages/utils/src/functions/urls.ts b/packages/utils/src/functions/urls.ts
index b29c2781a4..66e170bbda 100644
--- a/packages/utils/src/functions/urls.ts
+++ b/packages/utils/src/functions/urls.ts
@@ -7,6 +7,22 @@ export const isValidUrl = (url: string) => {
}
};
+const SAFE_LINK_SCHEMES = new Set(["http:", "https:", "mailto:"]);
+
+export function isSafeLinkHref(
+ href: string | null | undefined,
+): href is string {
+ if (!href) {
+ return false;
+ }
+
+ try {
+ return SAFE_LINK_SCHEMES.has(new URL(href).protocol);
+ } catch {
+ return false;
+ }
+}
+
export const getUrlFromString = (str: string) => {
if (isValidUrl(str)) return str;
try {