Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(conversations): keep formatting when copying a private note (#84189)

Andrew Maguire89d51764e95b
diff --git a/frontend/src/lib/utils/copyToClipboard.tsx b/frontend/src/lib/utils/copyToClipboard.tsx
index 90fca957998c..83dc3a0221a0 100644
--- a/frontend/src/lib/utils/copyToClipboard.tsx
+++ b/frontend/src/lib/utils/copyToClipboard.tsx
@@ -4,7 +4,7 @@ import { lemonToast } from '@posthog/lemon-ui'
export async function copyToClipboard(
value: string,
description: string = 'text',
- { silent = false }: { silent?: boolean } = {}
+ { silent = false, html }: { silent?: boolean; html?: string } = {}
): Promise<boolean> {
if (!navigator.clipboard) {
lemonToast.warning('Oops! Clipboard capabilities are only available over HTTPS or on localhost')
@@ -20,6 +20,25 @@ export async function copyToClipboard(
})
}
+ // Writing both formats lets a paste target that understands HTML keep the formatting, while
+ // plain-text targets still receive `value`. Browser support for `text/html` in a ClipboardItem
+ // is not universal, so a failure here falls through to the plain-text write below rather than
+ // failing the copy.
+ if (html && typeof ClipboardItem !== 'undefined' && navigator.clipboard.write) {
+ try {
+ await navigator.clipboard.write([
+ new ClipboardItem({
+ 'text/html': new Blob([html], { type: 'text/html' }),
+ 'text/plain': new Blob([value], { type: 'text/plain' }),
+ }),
+ ])
+ notifySuccess()
+ return true
+ } catch {
+ // Fall through to the plain-text paths.
+ }
+ }
+
try {
await navigator.clipboard.writeText(value)
notifySuccess()
diff --git a/products/conversations/frontend/components/Chat/Message.tsx b/products/conversations/frontend/components/Chat/Message.tsx
index b64e3216c20e..1f80a74b39d3 100644
--- a/products/conversations/frontend/components/Chat/Message.tsx
+++ b/products/conversations/frontend/components/Chat/Message.tsx
@@ -18,6 +18,7 @@ import { copyToClipboard } from 'lib/utils/copyToClipboard'
import type { AiReplyFeedbackRating, ChatMessage, MessageDeliveryStatus } from '../../types'
import { SupportMarkdown, SupportRichContentPreview } from '../Editor'
+import { richContentToHtml } from '../Editor/richContentToHtml'
import { TeamOnlyBadge } from './TeamOnlyBadge'
export interface MessageProps {
@@ -63,6 +64,12 @@ export function Message({
onSubmitAiReplyFeedback(rating)
}
+ function copyMessage(): void {
+ // Generated on demand rather than per render, since only a copy needs it.
+ const html = richContentToHtml(message.richContent as JSONContent | null)
+ void copyToClipboard(message.content, 'Message', { html: html ?? undefined })
+ }
+
function submitBadFeedbackText(): void {
if (aiReplyFeedbackDisabledReason || !feedbackText.trim() || !onSubmitAiReplyFeedback) {
return
@@ -151,7 +158,7 @@ export function Message({
size="xsmall"
icon={<IconCopy />}
noPadding
- onClick={() => void copyToClipboard(message.content, 'Message')}
+ onClick={copyMessage}
/>
</Tooltip>
</div>
diff --git a/products/conversations/frontend/components/Editor/SupportRichContentPreview.tsx b/products/conversations/frontend/components/Editor/SupportRichContentPreview.tsx
index 933f1a845740..ec1a7e4a9cbf 100644
--- a/products/conversations/frontend/components/Editor/SupportRichContentPreview.tsx
+++ b/products/conversations/frontend/components/Editor/SupportRichContentPreview.tsx
@@ -1,32 +1,17 @@
import './SupportEditor.scss'
-import { JSONContent, getSchema } from '@tiptap/core'
-import { Node as ProseMirrorNode } from '@tiptap/pm/model'
+import { JSONContent } from '@tiptap/core'
import { EditorContent } from '@tiptap/react'
import { useEffect, useMemo } from 'react'
import { useRichContentEditor } from 'lib/components/RichContentEditor'
import { cn } from 'lib/utils/css-classes'
+import { isRenderableRichContent } from './isRenderableRichContent'
import { SUPPORT_PREVIEW_EXTENSIONS } from './SupportEditor'
import { SupportMarkdown } from './SupportMarkdown'
import { useImageLightbox } from './useImageLightbox'
-let previewSchema: ReturnType<typeof getSchema> | null = null
-
-function isRenderableRichContent(content: JSONContent | null): content is JSONContent {
- if (!content) {
- return false
- }
- try {
- previewSchema = previewSchema ?? getSchema([...SUPPORT_PREVIEW_EXTENSIONS])
- ProseMirrorNode.fromJSON(previewSchema, content).check()
- return true
- } catch {
- return false
- }
-}
-
export interface SupportRichContentPreviewProps {
content: JSONContent | null
className?: string
diff --git a/products/conversations/frontend/components/Editor/isRenderableRichContent.ts b/products/conversations/frontend/components/Editor/isRenderableRichContent.ts
new file mode 100644
index 000000000000..37e42fa357de
--- /dev/null
+++ b/products/conversations/frontend/components/Editor/isRenderableRichContent.ts
@@ -0,0 +1,27 @@
+import { JSONContent, getSchema } from '@tiptap/core'
+import { Node as ProseMirrorNode } from '@tiptap/pm/model'
+
+import { SUPPORT_PREVIEW_EXTENSIONS } from './SupportEditor'
+
+let previewSchema: ReturnType<typeof getSchema> | null = null
+
+/**
+ * Whether stored rich content can be rendered against the preview schema.
+ *
+ * The request serializers accept any JSON-serializable shape, so a message can carry known node
+ * types in a structure the schema rejects. Everything that consumes a message's rich content has
+ * to agree on this verdict, otherwise a reader sees the plain-text fallback while another surface
+ * shows something else.
+ */
+export function isRenderableRichContent(content: JSONContent | null | undefined): content is JSONContent {
+ if (!content) {
+ return false
+ }
+ try {
+ previewSchema = previewSchema ?? getSchema([...SUPPORT_PREVIEW_EXTENSIONS])
+ ProseMirrorNode.fromJSON(previewSchema, content).check()
+ return true
+ } catch {
+ return false
+ }
+}
diff --git a/products/conversations/frontend/components/Editor/richContentToHtml.test.ts b/products/conversations/frontend/components/Editor/richContentToHtml.test.ts
new file mode 100644
index 000000000000..b626cf776a7c
--- /dev/null
+++ b/products/conversations/frontend/components/Editor/richContentToHtml.test.ts
@@ -0,0 +1,104 @@
+import { JSONContent, getSchema } from '@tiptap/core'
+import { DOMParser as ProseMirrorDOMParser } from '@tiptap/pm/model'
+
+import { RichContentNodeType } from 'lib/components/RichContentEditor/types'
+
+import { richContentToHtml } from './richContentToHtml'
+import { SUPPORT_EXTENSIONS } from './SupportEditor'
+
+// jest.setup.ts stubs this module out, which would make schema construction meaningless here
+jest.unmock('@tiptap/extension-code-block-lowlight')
+
+const paragraph = (...content: JSONContent[]): JSONContent => ({ type: 'paragraph', content })
+const text = (value: string): JSONContent => ({ type: 'text', text: value })
+const listItem = (...content: JSONContent[]): JSONContent => ({ type: 'listItem', content })
+
+/**
+ * What the composer does with a `text/html` paste: ProseMirror parses the HTML against the
+ * editor's own schema. Going through it here is the point of the test, because the bug this
+ * guards against is structure surviving generation but not the paste.
+ */
+function pasteIntoComposer(html: string): JSONContent {
+ const dom = document.createElement('div')
+ dom.innerHTML = html
+ const parser = ProseMirrorDOMParser.fromSchema(getSchema([...SUPPORT_EXTENSIONS]))
+ return parser.parse(dom).toJSON()
+}
+
+/** Node types and text only, so the comparison ignores attrs the schema fills in with defaults. */
+function outline(node: JSONContent): string {
+ if (node.type === 'text') {
+ return node.text ?? ''
+ }
+ if (!node.content) {
+ return `<${node.type}/>`
+ }
+ return `<${node.type}>${node.content.map(outline).join('')}</${node.type}>`
+}
+
+describe('richContentToHtml', () => {
+ // Copying the markdown form instead flattens all of these to a run of plain paragraphs,
+ // because the composer has no markdown paste parser: ProseMirror splits plain text on every
+ // run of newlines, so a blank line and a line break both become one ordinary paragraph
+ // boundary and list markers arrive as literal text.
+ test.each<[string, JSONContent, string]>([
+ [
+ 'paragraph breaks',
+ { type: 'doc', content: [paragraph(text('one')), paragraph(text('two'))] },
+ '<doc><paragraph>one</paragraph><paragraph>two</paragraph></doc>',
+ ],
+ [
+ 'a deliberate blank line between paragraphs',
+ { type: 'doc', content: [paragraph(text('one')), paragraph(), paragraph(text('two'))] },
+ '<doc><paragraph>one</paragraph><paragraph/><paragraph>two</paragraph></doc>',
+ ],
+ [
+ 'hard breaks within a paragraph',
+ { type: 'doc', content: [paragraph(text('one'), { type: 'hardBreak' }, text('two'))] },
+ '<doc><paragraph>one<hardBreak/>two</paragraph></doc>',
+ ],
+ [
+ 'list structure',
+ {
+ type: 'doc',
+ content: [
+ {
+ type: 'bulletList',
+ content: [listItem(paragraph(text('one'))), listItem(paragraph(text('two')))],
+ },
+ ],
+ },
+ '<doc><bulletList><listItem><paragraph>one</paragraph></listItem>' +
+ '<listItem><paragraph>two</paragraph></listItem></bulletList></doc>',
+ ],
+ ])('survives a paste into the composer: %s', (_name, content, expected) => {
+ const html = richContentToHtml(content)
+ expect(html).not.toBeNull()
+ expect(outline(pasteIntoComposer(html as string))).toEqual(expected)
+ })
+
+ it('keeps a mention readable outside PostHog and a node inside it', () => {
+ const content: JSONContent = {
+ type: 'doc',
+ content: [paragraph(text('ask '), { type: RichContentNodeType.Mention, attrs: { id: 5 } })],
+ }
+ const html = richContentToHtml(content) as string
+
+ // A mail client renders the text and ignores the tag it does not know
+ expect(html).toContain('@member:5')
+ // The composer restores the node from the tag, and its node view renders the name again
+ expect(outline(pasteIntoComposer(html))).toEqual(
+ `<doc><paragraph>ask <${RichContentNodeType.Mention}/></paragraph></doc>`
+ )
+ })
+
+ // Both of these render as the plain-text form for the reader, so the clipboard has to agree.
+ // `generateHTML` builds the document without checking it, so an invalid structure of known
+ // node types would otherwise serialize to HTML the message never displayed.
+ test.each<[string, JSONContent]>([
+ ['an unknown node type', { type: 'doc', content: [{ type: 'somethingUnknown' }] }],
+ ['known node types in an invalid structure', { type: 'doc', content: [text('bare text under doc')] }],
+ ])('returns null for %s, so the copy falls back to plain text', (_name, content) => {
+ expect(richContentToHtml(content)).toBeNull()
+ })
+})
diff --git a/products/conversations/frontend/components/Editor/richContentToHtml.ts b/products/conversations/frontend/components/Editor/richContentToHtml.ts
new file mode 100644
index 000000000000..a83dedfaccb2
--- /dev/null
+++ b/products/conversations/frontend/components/Editor/richContentToHtml.ts
@@ -0,0 +1,53 @@
+import { JSONContent, mergeAttributes } from '@tiptap/core'
+import { generateHTML } from '@tiptap/html'
+
+import { RichContentNodeMention } from 'lib/components/RichContentEditor/RichContentNodeMention'
+import { RichContentNodeType } from 'lib/components/RichContentEditor/types'
+
+import { isRenderableRichContent } from './isRenderableRichContent'
+import { SUPPORT_PREVIEW_EXTENSIONS } from './SupportEditor'
+
+/**
+ * A mention normally shows a member's name through a React node view, which never runs during
+ * plain HTML generation. Without a text child the element serializes empty, so a paste target that
+ * does not know the `ph-mention` tag, such as a mail client, drops the mention and loses a word
+ * from the sentence. The composer parses the node back from the tag and ignores this text, so it
+ * only shows up outside PostHog, where it matches what the markdown form has always carried.
+ */
+const ClipboardMention = RichContentNodeMention.extend({
+ renderHTML({ HTMLAttributes, node }) {
+ return [RichContentNodeType.Mention, mergeAttributes(HTMLAttributes), `@member:${node.attrs.id}`]
+ },
+})
+
+const CLIPBOARD_EXTENSIONS = SUPPORT_PREVIEW_EXTENSIONS.map((extension) =>
+ extension.name === RichContentNodeMention.name ? ClipboardMention : extension
+)
+
+/**
+ * Render a message's rich content as HTML, for putting on the clipboard alongside the plain-text
+ * markdown form.
+ *
+ * A message's plain-text field is markdown, and nothing that receives a paste parses markdown out
+ * of it. The reply composer is a ProseMirror editor with no markdown paste parser, so pasted text
+ * goes through ProseMirror's default handling, which splits on each run of newlines and makes
+ * every block a plain paragraph. A blank line, a line break, and a list item all end up as the
+ * same ordinary paragraph boundary, and markdown syntax plus the backslash escapes that
+ * `serializeToMarkdown` adds arrive as literal text. HTML is the format both the composer and
+ * mail clients already know how to parse.
+ *
+ * Returns null when the content cannot be rendered against the preview schema, in which case
+ * callers should copy the plain-text form on its own. That is the same verdict the reader sees,
+ * because `generateHTML` builds the document without checking it against the schema and would
+ * otherwise put content on the clipboard that the message never displayed.
+ */
+export function richContentToHtml(content: JSONContent | null | undefined): string | null {
+ if (!isRenderableRichContent(content)) {
+ return null
+ }
+ try {
+ return generateHTML(content, CLIPBOARD_EXTENSIONS)
+ } catch {
+ return null
+ }
+}