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.

Support markdown for in-app message render for campaigns

Kiran K626aebfb89e4
diff --git a/apps/web/lib/api/workflows/tiptap-json-to-markdown.ts b/apps/web/lib/api/workflows/tiptap-json-to-markdown.ts
new file mode 100644
index 0000000000..2535d6df91
--- /dev/null
+++ b/apps/web/lib/api/workflows/tiptap-json-to-markdown.ts
@@ -0,0 +1,161 @@
+import { EmailTemplateVariables } from "@/lib/types";
+
+export interface TiptapNode {
+ type: string;
+ text?: string;
+ attrs?: Record<string, any>;
+ content?: TiptapNode[];
+ marks?: Array<{ type: string; attrs?: Record<string, any> }>;
+}
+
+interface Options {
+ variables?: Partial<EmailTemplateVariables>;
+}
+
+function replaceVariables(
+ text: string,
+ variables: Partial<EmailTemplateVariables>,
+): string {
+ if (!variables || Object.keys(variables).length === 0) {
+ return text;
+ }
+
+ return text.replace(/{{\s*([\w\d_]+)\s*}}/g, (_, key) => {
+ return variables[key] ?? `{{${key}}}`;
+ });
+}
+
+// Convert TipTap JSON to Markdown (for in-app Messages)
+export function tiptapToMarkdown(
+ doc: TiptapNode | TiptapNode[],
+ opts?: Options,
+): string {
+ if (!doc) {
+ throw new Error("Document cannot be null or undefined");
+ }
+
+ const variables = opts?.variables || {};
+ const roots: TiptapNode[] = Array.isArray(doc) ? doc : [doc];
+
+ function walk(node: TiptapNode): string {
+ if (!node || typeof node !== "object" || !node.type) {
+ return "";
+ }
+
+ switch (node.type) {
+ case "doc": {
+ return (node.content || []).map((n) => walk(n)).join("\n\n");
+ }
+
+ // Paragraphs
+ case "paragraph": {
+ return (node.content || []).map((n) => walk(n)).join("");
+ }
+
+ // Text
+ case "text": {
+ let text = node.text || "";
+
+ text = replaceVariables(text, variables);
+
+ if (node.marks) {
+ node.marks.forEach((mark) => {
+ if (mark.type === "bold" || mark.type === "strong") {
+ text = `**${text}**`;
+ } else if (mark.type === "italic" || mark.type === "em") {
+ text = `*${text}*`;
+ } else if (mark.type === "link") {
+ const href = mark.attrs?.href || "";
+ text = `[${text}](${href})`;
+ }
+ });
+ }
+
+ return text;
+ }
+
+ // Headings (1-6)
+ case "heading": {
+ const level = node.attrs?.level || 1;
+ const text = (node.content || []).map((n) => walk(n)).join("");
+ const prefix = "#".repeat(level);
+
+ return `${prefix} ${text}`;
+ }
+
+ // Unordered lists
+ case "bulletList": {
+ return (node.content || [])
+ .map((item) => {
+ const content = walk(item);
+ return `- ${content}`;
+ })
+ .join("\n");
+ }
+
+ // Ordered lists
+ case "orderedList": {
+ const start = node.attrs?.start || 1;
+ return (node.content || [])
+ .map((item, index) => {
+ const content = walk(item);
+ return `${start + index}. ${content}`;
+ })
+ .join("\n");
+ }
+
+ // List items
+ case "listItem": {
+ return (node.content || []).map((n) => walk(n)).join("\n");
+ }
+
+ // Images
+ case "image": {
+ const src = node.attrs?.src || "";
+ const alt = node.attrs?.alt || "";
+
+ return `![${alt}](${src})`;
+ }
+
+ // Mentions
+ case "mention": {
+ const id = node.attrs?.id;
+
+ if (variables && id && variables[id] !== undefined) {
+ return variables[id] ?? "";
+ }
+
+ return `{{${id}}}`;
+ }
+
+ // Horizontal rule
+ case "horizontalRule": {
+ return "---";
+ }
+
+ // Blockquote
+ case "blockquote": {
+ const content = (node.content || [])
+ .map((n) => walk(n))
+ .join("\n")
+ .split("\n")
+ .map((line) => `> ${line}`)
+ .join("\n");
+ return content;
+ }
+
+ // Hard breaks
+ case "hardBreak":
+ case "hard_break": {
+ return " \n";
+ }
+
+ // Fallback: walk children
+ default: {
+ return (node.content || []).map((n) => walk(n)).join("");
+ }
+ }
+ }
+
+ return roots.map((r) => walk(r)).join("\n");
+}
diff --git a/apps/web/lib/api/workflows/tiptap-json-to-text.ts b/apps/web/lib/api/workflows/tiptap-json-to-text.ts
deleted file mode 100644
index f8cbbfd915..0000000000
--- a/apps/web/lib/api/workflows/tiptap-json-to-text.ts
+++ /dev/null
@@ -1,345 +0,0 @@
-import { EmailTemplateVariables } from "@/lib/types";
-
-const DEFAULTS: Required<Options> = {
- preserveNewlines: true,
- wordwrap: 0,
- preserveLinks: true,
- preserveImages: true,
- listIndent: " ",
- variables: {},
-};
-
-export interface TiptapNode {
- type: string;
- text?: string;
- attrs?: Record<string, any>;
- content?: TiptapNode[];
- marks?: Array<{ type: string; attrs?: Record<string, any> }>;
-}
-
-export interface Options {
- // Keep paragraph/heading line breaks as \n\n (default: true)
- preserveNewlines?: boolean;
-
- // Number of columns to wrap lines at (0 = disabled, default: 0)
- wordwrap?: number;
-
- // Include URLs after link text like "text (https://...)" (default: true)
- preserveLinks?: boolean;
-
- // Include image alt text or placeholder (default: false)
- preserveImages?: boolean;
-
- // Indentation string per list level (default: " ")
- listIndent?: string;
-
- // Template variables for replacement (default: {})
- variables?: Partial<EmailTemplateVariables>;
-}
-
-// Simple wordwrap implementation (does not break words if a single token > width)
-function wrapLine(line: string, width: number): string[] {
- if (!width || width <= 0) {
- return [line];
- }
-
- const words = line.split(/(\s+)/); // keep spaces as tokens
- const lines: string[] = [];
- let cur = "";
-
- for (const token of words) {
- if ((cur + token).length > width && cur.length > 0) {
- lines.push(cur.trimRight());
- cur = token;
- } else {
- cur += token;
- }
- }
-
- if (cur.length) {
- lines.push(cur.trimRight());
- }
-
- return lines;
-}
-
-function applyWrap(text: string, width: number): string {
- if (!width || width <= 0) {
- return text;
- }
-
- const paragraphs = text.split(/\n\n/);
- return paragraphs
- .map((p) => wrapLine(p.replace(/[\n\s]+/g, " "), width).join("\n"))
- .join("\n\n");
-}
-
-function escapeText(t: string): string {
- // This is plain-text -> no HTML; just normalize control chars
- return t.replace(/\u0000/g, "");
-}
-
-// Replace template variables
-function replaceVariables(
- text: string,
- variables: Partial<EmailTemplateVariables>,
-): string {
- if (!variables || Object.keys(variables).length === 0) {
- return text;
- }
-
- return text.replace(/{{\s*([\w\d_]+)\s*}}/g, (_, key) => {
- return variables[key] ?? `{{${key}}}`;
- });
-}
-
-// Process link href, stripping mailto: prefix and checking if it differs from text
-function processLinkHref(href: string, text: string): string | null {
- let cleanHref = href;
- // Strip mailto: prefix for email links
- if (cleanHref.startsWith("mailto:")) {
- cleanHref = cleanHref.substring(7);
- }
-
- // Only return href if it's different from the text content
- return cleanHref !== text.trim() ? cleanHref : null;
-}
-
-// Render marks like bold/italic — we do not preserve formatting as markup, but may preserve as-is
-function renderMarks(text: string, marks?: TiptapNode["marks"]): string {
- // For plain text messages we typically keep the raw text. Optionally we could add * or _ markers.
- return text;
-}
-
-// Small, secure converter from Tiptap JSON -> plain text.
-export function tiptapToPlainText(
- doc: TiptapNode | TiptapNode[],
- opts?: Options,
-): string {
- if (!doc) {
- throw new Error("Document cannot be null or undefined");
- }
-
- const conf = { ...DEFAULTS, ...(opts || {}) };
-
- const roots: TiptapNode[] = Array.isArray(doc) ? doc : [doc];
-
- function walk(
- node: TiptapNode,
- listState: { type?: string; index?: number; level?: number }[] = [],
- ): string {
- if (!node) {
- return "";
- }
-
- // Handle malformed nodes gracefully
- if (typeof node !== "object" || !node.type) {
- console.warn("Encountered malformed node:", node);
- return "";
- }
-
- switch (node.type) {
- case "doc":
- return (node.content || [])
- .map((n) => walk(n, listState))
- .join(conf.preserveNewlines ? "\n\n" : "\n");
-
- case "paragraph":
- return (node.content || []).map((n) => walk(n, listState)).join("");
-
- case "text": {
- let text = renderMarks(escapeText(node.text || ""), node.marks);
-
- // Replace template variables if any
- text = replaceVariables(text, conf.variables || {});
-
- // Process link marks
- if (conf.preserveLinks && node.marks) {
- node.marks.forEach((mark) => {
- if (mark.type === "link" && mark.attrs?.href) {
- const href = processLinkHref(mark.attrs.href, text);
- if (href) {
- text += ` ${href}`;
- }
- }
- });
- }
-
- return text;
- }
-
- case "heading": {
- const text = (node.content || [])
- .map((n) => walk(n, listState))
- .join("");
- // For headings, keep as a paragraph with an underline (optional). We'll keep simple: text + newline
- return text;
- }
-
- case "bulletList": {
- // Render each listItem with bullets; increment level
- const items = (node.content || [])
- .map((n) =>
- walk(n, [
- ...listState,
- { type: "bullet", level: listState.length + 1 },
- ]),
- )
- .join("\n");
- return items;
- }
-
- case "orderedList": {
- const start =
- node.attrs && node.attrs.start ? Number(node.attrs.start) : 1;
- const items = (node.content || [])
- .map((n, i) =>
- walk(n, [
- ...listState,
- {
- type: "ordered",
- index: start + i,
- level: listState.length + 1,
- },
- ]),
- )
- .join("\n");
- return items;
- }
-
- case "listItem": {
- // listItem typically contains a paragraph (and maybe nested lists)
- // Find first paragraph/text content
- const prefixParts: string[] = [];
- if (listState.length > 0) {
- const cur = listState[listState.length - 1];
- const indent = conf.listIndent.repeat((cur.level || 1) - 1);
-
- if (cur.type === "bullet") {
- prefixParts.push(indent + "• ");
- } else if (cur.type === "ordered") {
- prefixParts.push(indent + `${cur.index}. `);
- }
- }
-
- const inner = (node.content || [])
- .map((n) => walk(n, listState))
- .join("");
-
- // ensure lines within item are indented properly
- const innerLines = inner
- .split(/\n/)
- .map((l, idx) =>
- idx === 0
- ? l
- : conf.listIndent.repeat(
- listState[listState.length - 1]?.level || 1,
- ) + l,
- )
- .join("\n");
-
- return prefixParts.join("") + innerLines;
- }
-
- case "image": {
- if (!conf.preserveImages) {
- return "";
- }
-
- const alt =
- node.attrs && (node.attrs.alt || node.attrs.title || "image");
- const src = node.attrs && node.attrs.src;
-
- return alt
- ? `[image: ${alt}]${conf.preserveLinks && src ? ` (${src})` : ""}`
- : conf.preserveLinks && src
- ? src
- : "[image]";
- }
-
- case "hardBreak":
- case "br":
- return "\n";
-
- case "blockquote": {
- const inner = (node.content || [])
- .map((n) => walk(n, listState))
- .join("\n");
- return inner
- .split(/\n/)
- .map((l) => `> ${l}`)
- .join("\n");
- }
-
- case "codeBlock":
- case "code": {
- const text = (node.content || [])
- .map((n) => walk(n, listState))
- .join("");
-
- // Preserve as-is but mark with backticks for inline, fenced for block
- if (node.type === "codeBlock") {
- return `\n\n\u0060\u0060\u0060\n${text}\n\u0060\u0060\u0060\n\n`;
- }
-
- return `\`${text}\``;
- }
-
- case "hard_break":
- return "\n";
-
- case "mention": {
- // Mention node: show label if present, else @id
- const id = node.attrs?.id;
- const label = node.attrs?.label;
-
- if (conf.variables && id && conf.variables[id] !== undefined) {
- return conf.variables[id] ?? "";
- }
-
- return label || (id ? `@${id}` : "@mention");
- }
-
- case "link":
- case "a": {
- // In Tiptap, link is usually a mark not a node; but handle here defensively
- const text = (node.content || [])
- .map((n) => walk(n, listState))
- .join("");
- const href = node.attrs?.href;
-
- if (conf.preserveLinks && href) {
- const processedHref = processLinkHref(href, text);
-
- if (processedHref) {
- return `${text} ${processedHref}`;
- }
- }
-
- return text;
- }
-
- default: {
- // Fallback: walk children
- return (node.content || []).map((n) => walk(n, listState)).join("");
- }
- }
- }
-
- const raw = roots
- .map((r) => walk(r, []))
- .join(conf.preserveNewlines ? "\n\n" : "\n");
-
- // Normalize repeated blank lines to max two
- let normalized = raw.replace(/\n{3,}/g, "\n\n");
-
- // Trim each line but preserve intentional spaces
- normalized = normalized
- .split(/\n/)
- .map((l) => l.replace(/[\t\r]+/g, ""))
- .join("\n")
- .trim();
-
- // Apply wordwrap if requested
- return applyWrap(normalized, conf.wordwrap);
-}
diff --git a/apps/web/package.json b/apps/web/package.json
index 1c642c88a4..0c2c1a3b98 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -88,7 +88,7 @@
"js-cookie": "^3.0.5",
"json-2-csv": "^5.5.0",
"jszip": "^3.10.1",
- "linkify-react": "^4.1.3",
+ "linkify-react": "4.3.2",
"lucide-react": "^0.462.0",
"luxon": "^3.5.0",
"motion": "^12.23.22",
diff --git a/apps/web/ui/messages/message-markdown.tsx b/apps/web/ui/messages/message-markdown.tsx
new file mode 100644
index 0000000000..59e32edd9e
--- /dev/null
+++ b/apps/web/ui/messages/message-markdown.tsx
@@ -0,0 +1,79 @@
+import { cn } from "@dub/utils";
+import ReactMarkdown from "react-markdown";
+import "react-medium-image-zoom/dist/styles.css";
+import { ZoomImage } from "../shared/zoom-image";
+
+export function MessageMarkdown({
+ children,
+ components,
+ invert = false,
+}: {
+ children: string;
+ components?: any;
+ invert?: boolean;
+}) {
+ return (
+ <ReactMarkdown
+ className={cn(
+ "prose prose-sm prose-neutral max-w-none transition-all",
+ "prose-headings:font-semibold prose-headings:border-b prose-headings:pb-2",
+ "prose-h1:text-2xl prose-h1:font-bold prose-h1:mt-8 prose-h1:mb-4",
+ "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-6 prose-p:mb-4",
+ "prose-a:font-medium prose-a:underline prose-a:underline-offset-2",
+ "prose-strong:font-semibold",
+ "prose-em:italic",
+ "prose-code:px-1 prose-code:py-0.5 prose-code:rounded prose-code:text-xs prose-code:font-mono",
+ "prose-pre:border prose-pre:rounded-lg prose-pre:pr-9 prose-pre:pl-3 prose-pre:py-3 prose-pre:overflow-x-auto",
+ "prose-pre:code:bg-transparent prose-pre:code:p-0 prose-pre:code:text-sm",
+ "prose-blockquote:border-l-4 prose-blockquote:pl-4 prose-blockquote:italic",
+ "prose-ul:list-disc prose-ul:pl-6",
+ "prose-ol:list-decimal prose-ol:pl-6",
+ "prose-li:mb-1",
+ "prose-hr:my-8",
+ "prose-img:rounded-lg prose-img:border-1",
+ // Color styles (conditional based on invert)
+ 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-strong:text-white",
+ "prose-em:text-neutral-200",
+ "prose-code:text-neutral-100 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-hr:border-neutral-600",
+ "prose-img:border-neutral-600",
+ ]
+ : [
+ "prose-headings:text-neutral-900 prose-headings:border-neutral-200",
+ "prose-p:text-neutral-700",
+ "prose-a:text-neutral-600 hover:prose-a:text-neutral-700",
+ "prose-strong:text-neutral-900",
+ "prose-em:text-neutral-700",
+ "prose-code:text-neutral-800 prose-code:bg-neutral-100",
+ "prose-pre:bg-neutral-50 prose-pre:border-neutral-200",
+ "prose-blockquote:border-neutral-300 prose-blockquote:text-neutral-600",
+ "prose-ul:text-neutral-700",
+ "prose-ol:text-neutral-700",
+ "prose-hr:border-neutral-200",
+ "prose-img:border-neutral-200",
+ ],
+ )}
+ components={{
+ a: ({ node, ...props }) => (
+ <a {...props} target="_blank" rel="noopener noreferrer" />
+ ),
+ img: ({ node, ...props }) => <ZoomImage {...props} />,
+ ...components,
+ }}
+ >
+ {children}
+ </ReactMarkdown>
+ );
+}
diff --git a/apps/web/ui/messages/messages-panel.tsx b/apps/web/ui/messages/messages-panel.tsx
index 3268e7ab3c..d1fc248919 100644
--- a/apps/web/ui/messages/messages-panel.tsx
+++ b/apps/web/ui/messages/messages-panel.tsx
@@ -12,6 +12,7 @@ import Linkify from "linkify-react";
import { ChevronRight } from "lucide-react";
import { Fragment, useMemo, useRef, useState } from "react";
import { MessageInput } from "../shared/message-input";
+import { MessageMarkdown } from "./message-markdown";
interface Sender {
name: string | null;
@@ -449,20 +450,13 @@ function CampaignMessage({
<AnimatedSizeContainer height>
<div
className={cn(
- "max-w-lg overflow-hidden whitespace-pre-wrap",
- isExpanded ? "max-h-[1000px] px-4 py-2.5" : "max-h-0 px-4 py-0",
+ "max-w-lg overflow-hidden",
+ isExpanded ? "px-4 py-2.5" : "max-h-0 px-4 py-0",
)}
>
- <Linkify
- as="div"
- options={{
- target: "_blank",
- rel: "noopener noreferrer nofollow",
- className: "underline underline-offset-4",
- }}
- >
+ <MessageMarkdown invert={isMySide}>
{message.text}
- </Linkify>
+ </MessageMarkdown>
</div>
</AnimatedSizeContainer>
</div>
diff --git a/packages/ui/package.json b/packages/ui/package.json
index 17b14545f4..ace574f035 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -98,7 +98,7 @@
"embla-carousel-react": "^8.1.7",
"js-cookie": "^3.0.5",
"js-sha256": "^0.11.0",
- "linkify-react": "^4.1.3",
+ "linkify-react": "^4.3.2",
"linkifyjs": "^4.1.3",
"lucide-react": "^0.462.0",
"motion": "^12.23.22",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 2ac1215b28..330791f619 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -252,8 +252,8 @@ importers:
specifier: ^3.10.1
version: 3.10.1
linkify-react:
- specifier: ^4.1.3
+ specifier: 4.3.2
lucide-react:
specifier: ^0.462.0
version: 0.462.0([email protected])
@@ -848,8 +848,8 @@ importers:
specifier: ^0.11.0
version: 0.11.0
linkify-react:
- specifier: ^4.1.3
+ specifier: ^4.3.2
linkifyjs:
specifier: ^4.1.3
version: 4.1.3
@@ -9821,8 +9821,8 @@ packages:
resolution: {integrity: sha512-5aHCbzQRADcdP+ATqnDuhhJ/MRIqDkZX5pyjFHRRysS8vZ5AbqGEoFIb6pYHPZ+L/OC2Lc+xT8uHVVR5CAK/wQ==}
- resolution: {integrity: sha512-rhI3zM/fxn5BfRPHfi4r9N7zgac4vOIxub1wHIWXLA5ENTMs+BGaIaFO1D1PhmxgwhIKmJz3H7uCP0Dg5JwSlA==}
+ resolution: {integrity: sha512-mi744h1hf+WDsr+paJgSBBgYNLMWNSHyM9V9LVUo03RidNGdw1VpI7Twnt+K3pEh3nIzB4xiiAgZxpd61ItKpQ==}
peerDependencies:
linkifyjs: ^4.0.0
react: '>= 15.0.0'
@@ -24968,12 +24968,12 @@ snapshots:
dependencies:
uc.micro: 2.1.0
dependencies:
linkifyjs: 4.1.3
react: 19.1.1
dependencies:
linkifyjs: 4.3.2
react: 19.1.1