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.

chore(frontend): extract shared tiptap markdown converter (#69696)

Matt Puab95e3fee0c99
diff --git a/frontend/src/lib/components/Cards/TextCard/TextCard.tsx b/frontend/src/lib/components/Cards/TextCard/TextCard.tsx
index d36a5beaa758..04eddd5bf460 100644
--- a/frontend/src/lib/components/Cards/TextCard/TextCard.tsx
+++ b/frontend/src/lib/components/Cards/TextCard/TextCard.tsx
@@ -15,7 +15,7 @@ import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
import { DashboardPlacement, DashboardTile, QueryBasedInsightModel } from '~/types'
-import { markdownToTextCardDoc, TEXT_CARD_MARKDOWN_READONLY_EXTENSIONS } from './textCardMarkdown'
+import { TEXT_CARD_MARKDOWN_READONLY_EXTENSIONS, textCardConverter } from './textCardMarkdown'
interface TextCardProps extends React.HTMLAttributes<HTMLDivElement>, Resizeable {
textTile: DashboardTile<QueryBasedInsightModel>
@@ -38,7 +38,7 @@ interface TextCardBodyProps extends Pick<React.HTMLAttributes<HTMLDivElement>, '
}
function TextContentImpl({ text, closeDetails, className }: TextCardBodyProps): JSX.Element {
- const initialDoc = useMemo(() => markdownToTextCardDoc(text), [text])
+ const initialDoc = useMemo(() => textCardConverter.markdownToDoc(text), [text])
const editor = useRichContentEditor({
extensions: TEXT_CARD_MARKDOWN_READONLY_EXTENSIONS,
diff --git a/frontend/src/lib/components/Cards/TextCard/TextCardMarkdownEditor.tsx b/frontend/src/lib/components/Cards/TextCard/TextCardMarkdownEditor.tsx
index 713400e937c2..a9d3915c6d72 100644
--- a/frontend/src/lib/components/Cards/TextCard/TextCardMarkdownEditor.tsx
+++ b/frontend/src/lib/components/Cards/TextCard/TextCardMarkdownEditor.tsx
@@ -4,7 +4,7 @@ import { Extensions } from '@tiptap/react'
import { TextContent } from 'lib/components/Cards/TextCard/TextCard'
import { RichMarkdownEditor } from 'lib/components/MarkdownEditor/rich/RichMarkdownEditor'
-import { markdownToTextCardDoc, textCardDocToMarkdown, TEXT_CARD_MARKDOWN_EXTENSIONS } from './textCardMarkdown'
+import { TEXT_CARD_MARKDOWN_EXTENSIONS, textCardConverter } from './textCardMarkdown'
const TEXT_CARD_MARKDOWN_EDITOR_EXTENSIONS: Extensions = [
...TEXT_CARD_MARKDOWN_EXTENSIONS,
@@ -31,8 +31,8 @@ export function TextCardMarkdownEditor({
maxLength={4000}
dataAttr="text-card-edit-area"
extensions={TEXT_CARD_MARKDOWN_EDITOR_EXTENSIONS}
- markdownToDoc={markdownToTextCardDoc}
- docToMarkdown={textCardDocToMarkdown}
+ markdownToDoc={textCardConverter.markdownToDoc}
+ docToMarkdown={textCardConverter.docToMarkdown}
renderPreview={(markdown) => <TextContent text={markdown} className="LemonTextArea--preview" />}
autoFocus
/>
diff --git a/frontend/src/lib/components/Cards/TextCard/TextCardModal.tsx b/frontend/src/lib/components/Cards/TextCard/TextCardModal.tsx
index a667f83b511e..0af89da63c6e 100644
--- a/frontend/src/lib/components/Cards/TextCard/TextCardModal.tsx
+++ b/frontend/src/lib/components/Cards/TextCard/TextCardModal.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import { Field, Form } from 'kea-forms'
import { useCallback, useState } from 'react'
-import { isTextCardMarkdownRoundTripSafe } from 'lib/components/Cards/TextCard/textCardMarkdown'
+import { textCardConverter } from 'lib/components/Cards/TextCard/textCardMarkdown'
import { TextCardModalBodyField } from 'lib/components/Cards/TextCard/TextCardModalBodyField'
import { textCardModalLogic } from 'lib/components/Cards/TextCard/textCardModalLogic'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
@@ -32,7 +32,7 @@ export function TextCardModal({
const [initialBody] = useState(() =>
resolvedTileId !== 'new' ? dashboard.tiles?.find((tile) => tile.id === resolvedTileId)?.text?.body || '' : ''
)
- const shouldUseLegacyMarkdownEditor = !isTextCardMarkdownRoundTripSafe(initialBody)
+ const shouldUseLegacyMarkdownEditor = !textCardConverter.isRoundTripSafe(initialBody)
const hasUnsavedInput = (textTile?.body || '') !== initialBody
const handleClose = useCallback((): void => {
diff --git a/frontend/src/lib/components/Cards/TextCard/textCardMarkdown.test.ts b/frontend/src/lib/components/Cards/TextCard/textCardMarkdown.test.ts
index 9aead59359b1..fdb5a2f9c984 100644
--- a/frontend/src/lib/components/Cards/TextCard/textCardMarkdown.test.ts
+++ b/frontend/src/lib/components/Cards/TextCard/textCardMarkdown.test.ts
@@ -1,16 +1,14 @@
import { JSONContent } from '@tiptap/core'
import {
- isTextCardMarkdownRoundTripSafe,
- markdownToTextCardDoc,
- textCardDocToMarkdown,
TEXT_CARD_MARKDOWN_EXTENSIONS,
TEXT_CARD_MARKDOWN_READONLY_EXTENSIONS,
+ textCardConverter,
} from './textCardMarkdown'
describe('textCardMarkdown', () => {
it.each([undefined, null, '', ' \n\t '])('returns an empty doc for blank markdown: %p', (markdown) => {
- expect(markdownToTextCardDoc(markdown)).toEqual({
+ expect(textCardConverter.markdownToDoc(markdown)).toEqual({
type: 'doc',
content: [{ type: 'paragraph' }],
})
@@ -18,7 +16,7 @@ describe('textCardMarkdown', () => {
it('serializes an empty tiptap doc to an empty markdown string', () => {
expect(
- textCardDocToMarkdown({
+ textCardConverter.docToMarkdown({
type: 'doc',
content: [{ type: 'paragraph' }],
})
@@ -26,15 +24,15 @@ describe('textCardMarkdown', () => {
})
it('parses legacy markdown into tiptap content', () => {
- const doc = markdownToTextCardDoc('# Heading\n\n- Item 1\n- Item 2')
+ const doc = textCardConverter.markdownToDoc('# Heading\n\n- Item 1\n- Item 2')
expect(doc.type).toBe('doc')
expect(doc.content?.[0]).toMatchObject({ type: 'heading', attrs: { level: 1 } })
expect(doc.content?.[1]).toMatchObject({ type: 'bulletList' })
})
it('serializes tiptap content back to markdown', () => {
- const markdown = textCardDocToMarkdown(
- markdownToTextCardDoc('**bold**\n\n1. first\n2. second\n\n![img](https://example.com/image.png)')
+ const markdown = textCardConverter.docToMarkdown(
+ textCardConverter.markdownToDoc('**bold**\n\n1. first\n2. second\n\n![img](https://example.com/image.png)')
)
expect(markdown).toContain('**bold**')
@@ -45,14 +43,14 @@ describe('textCardMarkdown', () => {
it('parses and serializes strikethrough markdown', () => {
const input = '~~crossed~~ and **bold**'
- const doc = markdownToTextCardDoc(input)
+ const doc = textCardConverter.markdownToDoc(input)
const paragraph = doc.content?.[0]
expect(paragraph?.type).toBe('paragraph')
const strikeText = paragraph?.content?.find(
(n) => n.type === 'text' && n.marks?.some((m) => m.type === 'strike')
)
expect(strikeText).toMatchObject({ type: 'text', text: 'crossed' })
- expect(textCardDocToMarkdown(doc)).toContain('~~crossed~~')
+ expect(textCardConverter.docToMarkdown(doc)).toContain('~~crossed~~')
})
it('preserves resized image dimensions when serializing markdown', () => {
@@ -71,8 +69,8 @@ describe('textCardMarkdown', () => {
],
}
- const markdown = textCardDocToMarkdown(doc)
- const roundTripDoc = markdownToTextCardDoc(markdown)
+ const markdown = textCardConverter.docToMarkdown(doc)
+ const roundTripDoc = textCardConverter.markdownToDoc(markdown)
const imageNode = roundTripDoc.content?.[0]
expect(markdown).toContain('<img ')
@@ -90,7 +88,7 @@ describe('textCardMarkdown', () => {
'- [x] done\n- [ ] pending',
'![img](https://example.com/test.png)',
])('identifies round-trip safe markdown: %p', (markdown) => {
- expect(isTextCardMarkdownRoundTripSafe(markdown)).toBe(true)
+ expect(textCardConverter.isRoundTripSafe(markdown)).toBe(true)
})
it('does not append storage metadata markers to markdown output', () => {
@@ -114,8 +112,8 @@ describe('textCardMarkdown', () => {
],
}
- const markdown = textCardDocToMarkdown(richDoc)
- const roundTripDoc = markdownToTextCardDoc(markdown)
+ const markdown = textCardConverter.docToMarkdown(richDoc)
+ const roundTripDoc = textCardConverter.markdownToDoc(markdown)
expect(markdown).toContain('++underlined++')
expect(markdown).toContain('`inline code`')
@@ -126,8 +124,8 @@ describe('textCardMarkdown', () => {
it('supports underline markdown round-trip', () => {
const markdown = '++underlined++'
- const doc = markdownToTextCardDoc(markdown)
- const serialized = textCardDocToMarkdown(doc)
+ const doc = textCardConverter.markdownToDoc(markdown)
+ const serialized = textCardConverter.docToMarkdown(doc)
expect(serialized).toContain('++underlined++')
})
@@ -153,8 +151,8 @@ describe('textCardMarkdown', () => {
],
}
- const markdown = textCardDocToMarkdown(doc)
- const roundTripDoc = markdownToTextCardDoc(markdown)
+ const markdown = textCardConverter.docToMarkdown(doc)
+ const roundTripDoc = textCardConverter.markdownToDoc(markdown)
const wordArtNode = roundTripDoc.content?.[0]?.content?.find((node) => node.type === 'wordArt')
expect(markdown).toContain(`<span data-word-art="${expectedStyle}"`)
@@ -164,7 +162,7 @@ describe('textCardMarkdown', () => {
expect(markdown).toContain(`data-word-art-size="${expectedSize}"`)
}
expect(wordArtNode?.attrs).toEqual({ text, style: expectedStyle, size: expectedSize })
- expect(isTextCardMarkdownRoundTripSafe(markdown)).toBe(true)
+ expect(textCardConverter.isRoundTripSafe(markdown)).toBe(true)
})
it('uses non-clickable links while editing and clickable links in readonly', () => {
diff --git a/frontend/src/lib/components/Cards/TextCard/textCardMarkdown.ts b/frontend/src/lib/components/Cards/TextCard/textCardMarkdown.ts
index bde05050d3d6..519d9d38b671 100644
--- a/frontend/src/lib/components/Cards/TextCard/textCardMarkdown.ts
+++ b/frontend/src/lib/components/Cards/TextCard/textCardMarkdown.ts
@@ -1,11 +1,10 @@
-import { JSONContent } from '@tiptap/core'
import { Image } from '@tiptap/extension-image'
-import { Link } from '@tiptap/extension-link'
-import { TaskItem, TaskList } from '@tiptap/extension-list'
-import { MarkdownManager } from '@tiptap/markdown'
-import StarterKit from '@tiptap/starter-kit'
-import { expandFlattenedMarkdownTables } from 'lib/utils/markdown'
+import {
+ MARKDOWN_BASE_EDITABLE_EXTENSIONS,
+ MARKDOWN_BASE_READONLY_EXTENSIONS,
+} from 'lib/components/MarkdownEditor/shared/markdownExtensions'
+import { createTiptapMarkdownConverter } from 'lib/utils/markdown'
import { WordArtExtension } from './WordArt/WordArtExtension'
@@ -38,30 +37,9 @@ const TextCardImageExtension = Image.extend({
},
})
-const TEXT_CARD_MARKDOWN_BASE_EXTENSIONS = [
- StarterKit.configure({
- heading: {
- levels: [1, 2, 3],
- },
- link: false,
- }),
- TaskList,
- TaskItem.configure({ nested: true }),
- WordArtExtension,
-]
-
-const TEXT_CARD_MARKDOWN_BASE_EDITABLE_EXTENSIONS = [
- ...TEXT_CARD_MARKDOWN_BASE_EXTENSIONS,
- Link.configure({ openOnClick: false }),
-]
-
-const TEXT_CARD_MARKDOWN_BASE_READONLY_EXTENSIONS = [
- ...TEXT_CARD_MARKDOWN_BASE_EXTENSIONS,
- Link.configure({ openOnClick: true }),
-]
-
export const TEXT_CARD_MARKDOWN_EXTENSIONS = [
- ...TEXT_CARD_MARKDOWN_BASE_EDITABLE_EXTENSIONS,
+ ...MARKDOWN_BASE_EDITABLE_EXTENSIONS,
+ WordArtExtension,
TextCardImageExtension.configure({
HTMLAttributes: {
draggable: 'true',
@@ -77,7 +55,8 @@ export const TEXT_CARD_MARKDOWN_EXTENSIONS = [
]
export const TEXT_CARD_MARKDOWN_READONLY_EXTENSIONS = [
- ...TEXT_CARD_MARKDOWN_BASE_READONLY_EXTENSIONS,
+ ...MARKDOWN_BASE_READONLY_EXTENSIONS,
+ WordArtExtension,
TextCardImageExtension.configure({
HTMLAttributes: {
draggable: 'false',
@@ -88,94 +67,4 @@ export const TEXT_CARD_MARKDOWN_READONLY_EXTENSIONS = [
}),
]
-const markdownManager = new MarkdownManager({
- extensions: TEXT_CARD_MARKDOWN_EXTENSIONS,
-})
-
-const EMPTY_DOC_CONTENT: JSONContent['content'] = [{ type: 'paragraph' }]
-
-export const EMPTY_TEXT_CARD_DOC: JSONContent = {
- type: 'doc',
- content: EMPTY_DOC_CONTENT,
-}
-
-function isEffectivelyEmptyTextCardDoc(doc: JSONContent): boolean {
- if (doc.type !== 'doc') {
- return false
- }
-
- if (!doc.content || doc.content.length === 0) {
- return true
- }
-
- if (doc.content.length !== 1 || doc.content[0].type !== 'paragraph') {
- return false
- }
-
- const paragraphContent = doc.content[0].content
- if (!paragraphContent || paragraphContent.length === 0) {
- return true
- }
-
- return paragraphContent.every((node) => node.type === 'text' && !node.text)
-}
-
-export function markdownToTextCardDoc(markdown: string | null | undefined): JSONContent {
- if (!markdown) {
- return EMPTY_TEXT_CARD_DOC
- }
-
- if (markdown.trim() === '') {
- return EMPTY_TEXT_CARD_DOC
- }
-
- try {
- const parsed = markdownManager.parse(expandFlattenedMarkdownTables(markdown)) as JSONContent
- if (parsed.type === 'doc') {
- return parsed
- }
- } catch {
- // Fall through to plain paragraph fallback for malformed legacy markdown.
- }
-
- return {
- type: 'doc',
- content: [
- {
- type: 'paragraph',
- content: [{ type: 'text', text: markdown }],
- },
- ],
- }
-}
-
-export function textCardDocToMarkdown(doc: JSONContent): string {
- try {
- if (isEffectivelyEmptyTextCardDoc(doc)) {
- return ''
- }
-
- const markdown = markdownManager.serialize(doc).trimEnd()
- if (!markdown) {
- return ''
- }
- return markdown
- } catch {
- return ''
- }
-}
-
-export function isTextCardMarkdownRoundTripSafe(markdown: string | null | undefined): boolean {
- if (!markdown || markdown.trim() === '') {
- return true
- }
-
- try {
- const expanded = expandFlattenedMarkdownTables(markdown)
- const originalDoc = markdownManager.parse(expanded) as JSONContent
- const roundTripDoc = markdownManager.parse(markdownManager.serialize(originalDoc).trimEnd()) as JSONContent
- return JSON.stringify(originalDoc) === JSON.stringify(roundTripDoc)
- } catch {
- return false
- }
-}
+export const textCardConverter = createTiptapMarkdownConverter(TEXT_CARD_MARKDOWN_EXTENSIONS)
diff --git a/frontend/src/lib/components/MarkdownEditor/inline/InlineRichMarkdownEditor.stories.tsx b/frontend/src/lib/components/MarkdownEditor/inline/InlineRichMarkdownEditor.stories.tsx
index 0febe061e317..de1cc558a45a 100644
--- a/frontend/src/lib/components/MarkdownEditor/inline/InlineRichMarkdownEditor.stories.tsx
+++ b/frontend/src/lib/components/MarkdownEditor/inline/InlineRichMarkdownEditor.stories.tsx
@@ -2,11 +2,7 @@ import type { Meta, StoryObj } from '@storybook/react'
import { Placeholder } from '@tiptap/extension-placeholder'
import { useState } from 'react'
-import {
- markdownToTextCardDoc,
- textCardDocToMarkdown,
- TEXT_CARD_MARKDOWN_EXTENSIONS,
-} from 'lib/components/Cards/TextCard/textCardMarkdown'
+import { TEXT_CARD_MARKDOWN_EXTENSIONS, textCardConverter } from 'lib/components/Cards/TextCard/textCardMarkdown'
import { InlineRichMarkdownEditor, InlineRichMarkdownEditorProps } from './InlineRichMarkdownEditor'
@@ -24,8 +20,8 @@ const INLINE_EXTENSIONS_BUBBLE_AND_SLASH = [
const storyDefaults = {
extensions: INLINE_EXTENSIONS,
- markdownToDoc: markdownToTextCardDoc,
- docToMarkdown: textCardDocToMarkdown,
+ markdownToDoc: textCardConverter.markdownToDoc,
+ docToMarkdown: textCardConverter.docToMarkdown,
dataAttr: 'story-inline-rich-markdown-editor',
}
@@ -56,7 +52,7 @@ export const WithMarkdown: Story = {
export const WithSlashCommands: Story = {
args: {
value: 'Type / in the editor to open the command menu.',
- showSlashCommands: true,
+ controls: { slashCommands: true },
},
}
@@ -67,8 +63,6 @@ export const BubbleMenuAndSlashCommands: Story = {
value: `Select this sentence to open the **bubble** toolbar (bold, link, image, emoji, etc.).
On a new line, type \`/\` to open **slash** commands — same capabilities grouped as Style and Insert.`,
- showSlashCommands: true,
- showBubbleImageUpload: true,
- showBubbleEmoji: true,
+ controls: { slashCommands: true, imageUpload: true, emoji: true },
},
}
diff --git a/frontend/src/lib/components/MarkdownEditor/inline/InlineRichMarkdownEditor.test.tsx b/frontend/src/lib/components/MarkdownEditor/inline/InlineRichMarkdownEditor.test.tsx
index 07c111e4c3df..df3f0a1b3ed9 100644
--- a/frontend/src/lib/components/MarkdownEditor/inline/InlineRichMarkdownEditor.test.tsx
+++ b/frontend/src/lib/components/MarkdownEditor/inline/InlineRichMarkdownEditor.test.tsx
@@ -84,11 +84,11 @@ describe('InlineRichMarkdownEditor', () => {
expect(counter).toHaveClass('text-danger')
})
- it('hides character count footer when showCharacterCount is false', () => {
+ it('hides character count footer when characterCount is off', () => {
render(
<InlineRichMarkdownEditor
value="hello"
- showCharacterCount={false}
+ controls={{ characterCount: false }}
extensions={[]}
markdownToDoc={() => ({ type: 'doc', content: [] })}
docToMarkdown={() => 'hello'}
@@ -214,11 +214,11 @@ describe('InlineRichMarkdownEditor', () => {
expect(container.querySelector('.my-inline-editor')).toBeInTheDocument()
})
- it('accepts showSlashCommands without throwing', () => {
+ it('accepts slash commands without throwing', () => {
const { container } = render(
<InlineRichMarkdownEditor
value=""
- showSlashCommands
+ controls={{ slashCommands: true }}
extensions={[]}
markdownToDoc={() => ({ type: 'doc', content: [] })}
docToMarkdown={() => ''}
@@ -239,8 +239,7 @@ describe('InlineRichMarkdownEditor', () => {
const { container } = render(
<InlineRichMarkdownEditor
value=""
- showBubbleImageUpload
- showSlashCommands
+ controls={{ imageUpload: true, slashCommands: true }}
extensions={[]}
markdownToDoc={() => ({ type: 'doc', content: [] })}
docToMarkdown={() => ''}
diff --git a/frontend/src/lib/components/MarkdownEditor/inline/InlineRichMarkdownEditor.tsx b/frontend/src/lib/components/MarkdownEditor/inline/InlineRichMarkdownEditor.tsx
index 8ec108318e8d..3d4409eb7e6d 100644
--- a/frontend/src/lib/components/MarkdownEditor/inline/InlineRichMarkdownEditor.tsx
+++ b/frontend/src/lib/components/MarkdownEditor/inline/InlineRichMarkdownEditor.tsx
@@ -30,18 +30,21 @@ export type InlineRichMarkdownEditorProps = {
extensions: Extensions
markdownToDoc: (markdown: string | null | undefined) => JSONContent
docToMarkdown: (doc: JSONContent) => string
- /** When false, hides the character count footer */
- showCharacterCount?: boolean
autoFocus?: boolean
className?: string
- /** Bubble menu: image upload (requires object storage when enabled) */
- showBubbleImageUpload?: boolean
- /** Bubble menu: emoji picker */
- showBubbleEmoji?: boolean
- /** Append `/` slash command menu (grouped sections, filter as you type) */
- showSlashCommands?: boolean
- /** Custom slash items when `showSlashCommands` is true (defaults match bubble / rich formatting toolbar) */
- slashCommands?: InlineMarkdownSlashCommandItem[]
+ /** Toggle individual features on/off. Any key omitted keeps its default. */
+ controls?: {
+ /** Bubble menu + slash-command image upload (requires object storage). Default true. */
+ imageUpload?: boolean
+ /** Bubble menu emoji picker. Default true. */
+ emoji?: boolean
+ /** Append `/` slash command menu (grouped sections, filter as you type). Default false. */
+ slashCommands?: boolean
+ /** Character count footer. Default true. */
+ characterCount?: boolean
+ }
+ /** Custom slash items when `controls.slashCommands` is on (defaults match bubble / rich formatting toolbar) */
+ slashCommandItems?: InlineMarkdownSlashCommandItem[]
}
/**
@@ -91,14 +94,15 @@ export function InlineRichMarkdownEditor({
extensions,
markdownToDoc,
docToMarkdown,
- showCharacterCount = true,
autoFocus = false,
className = '',
- showBubbleImageUpload = true,
- showBubbleEmoji = true,
- showSlashCommands = false,
- slashCommands,
+ controls,
+ slashCommandItems,
}: InlineRichMarkdownEditorProps): JSX.Element {
+ const showImageUpload = controls?.imageUpload ?? true
+ const showEmoji = controls?.emoji ?? true
+ const showSlashCommands = controls?.slashCommands ?? false
+ const showCharacterCount = controls?.characterCount ?? true
const [linkUrl, setLinkUrl] = useState('')
const [showLinkPopover, setShowLinkPopover] = useState(false)
const [linkPopoverReferenceElement, setLinkPopoverReferenceElement] = useState<HTMLElement | null>(null)
@@ -143,11 +147,11 @@ export function InlineRichMarkdownEditor({
...extensions,
createInlineMarkdownSlashCommandsExtension(
INLINE_MARKDOWN_SLASH_COMMANDS_PLUGIN_KEY,
- slashCommands ?? DEFAULT_INLINE_MARKDOWN_SLASH_COMMANDS,
+ slashCommandItems ?? DEFAULT_INLINE_MARKDOWN_SLASH_COMMANDS,
{ slashImageHostRef, slashLinkHostRef }
),
]
- }, [extensions, showSlashCommands, slashCommands])
+ }, [extensions, showSlashCommands, slashCommandItems])
const editor = useRichContentEditor({
extensions: resolvedExtensions,
@@ -186,7 +190,7 @@ export function InlineRichMarkdownEditor({
pick: () => {
slashImageFileInputRef.current?.click()
},
- showSlashImageUpload: showBubbleImageUpload,
+ showSlashImageUpload: showImageUpload,
}
slashLinkHostRef.current = {
openLinkPopover: () => {
@@ -224,8 +228,8 @@ export function InlineRichMarkdownEditor({
linkPopoverReferenceElement={linkPopoverReferenceElement}
clearLinkPopoverReference={clearLinkPopoverReference}
alternativeDropTargetRef={dropRef}
- showImageUpload={showBubbleImageUpload}
- showEmoji={showBubbleEmoji}
+ showImageUpload={showImageUpload}
+ showEmoji={showEmoji}
/>
) : null}
{showCharacterCount ? (
diff --git a/frontend/src/lib/components/MarkdownEditor/rich/RichMarkdownEditor.stories.tsx b/frontend/src/lib/components/MarkdownEditor/rich/RichMarkdownEditor.stories.tsx
index e452c46f4446..39ced3e8fcbd 100644
--- a/frontend/src/lib/components/MarkdownEditor/rich/RichMarkdownEditor.stories.tsx
+++ b/frontend/src/lib/components/MarkdownEditor/rich/RichMarkdownEditor.stories.tsx
@@ -2,11 +2,7 @@ import type { Meta, StoryObj } from '@storybook/react'
import { Placeholder } from '@tiptap/extension-placeholder'
import { useState } from 'react'
-import {
- markdownToTextCardDoc,
- textCardDocToMarkdown,
- TEXT_CARD_MARKDOWN_EXTENSIONS,
-} from 'lib/components/Cards/TextCard/textCardMarkdown'
+import { TEXT_CARD_MARKDOWN_EXTENSIONS, textCardConverter } from 'lib/components/Cards/TextCard/textCardMarkdown'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
import { RichMarkdownEditor, type RichMarkdownEditorProps } from './RichMarkdownEditor'
@@ -19,8 +15,8 @@ const TEXT_CARD_LIKE_EXTENSIONS = [
const storyDefaults = {
extensions: TEXT_CARD_LIKE_EXTENSIONS,
- markdownToDoc: markdownToTextCardDoc,
- docToMarkdown: textCardDocToMarkdown,
+ markdownToDoc: textCardConverter.markdownToDoc,
+ docToMarkdown: textCardConverter.docToMarkdown,
renderPreview: (markdown: string): JSX.Element => <LemonMarkdown>{markdown}</LemonMarkdown>,
dataAttr: 'story-rich-markdown-editor',
}
diff --git a/frontend/src/lib/components/MarkdownEditor/shared/markdownExtensions.ts b/frontend/src/lib/components/MarkdownEditor/shared/markdownExtensions.ts
new file mode 100644
index 000000000000..3f464d45c0e2
--- /dev/null
+++ b/frontend/src/lib/components/MarkdownEditor/shared/markdownExtensions.ts
@@ -0,0 +1,20 @@
+import { Link } from '@tiptap/extension-link'
+import { TaskItem, TaskList } from '@tiptap/extension-list'
+import StarterKit from '@tiptap/starter-kit'
+
+// Shared building blocks for the markdown editors (text card, AI prompt, etc). Each editor starts
+// from these and only layers on what makes it different — images, a placeholder, tables, and so on.
+const MARKDOWN_BASE_EXTENSIONS = [
+ StarterKit.configure({
+ heading: {
+ levels: [1, 2, 3],
+ },
+ link: false,
+ }),
+ TaskList,
+ TaskItem.configure({ nested: true }),
+]
+
+export const MARKDOWN_BASE_EDITABLE_EXTENSIONS = [...MARKDOWN_BASE_EXTENSIONS, Link.configure({ openOnClick: false })]
+
+export const MARKDOWN_BASE_READONLY_EXTENSIONS = [...MARKDOWN_BASE_EXTENSIONS, Link.configure({ openOnClick: true })]
diff --git a/frontend/src/lib/utils/markdown.ts b/frontend/src/lib/utils/markdown.ts
index a06f48cade37..71f82bd759b7 100644
--- a/frontend/src/lib/utils/markdown.ts
+++ b/frontend/src/lib/utils/markdown.ts
@@ -1,3 +1,6 @@
+import { JSONContent } from '@tiptap/core'
+import { MarkdownManager } from '@tiptap/markdown'
+import { Extensions } from '@tiptap/react'
import { marked } from 'marked'
const TABLE_DELIMITER_SEGMENT_RE = /^\|(?:\s*:?-{2,}:?\s*\|)+\s*$/
@@ -137,3 +140,108 @@ export function stripMarkdown(markdown: string): string {
// Replace multiple consecutive newlines (3+) with just 2 to preserve paragraph breaks
return result.replace(/\n{3,}/g, '\n\n').trim()
}
+
+/** A TipTap doc holding a single empty paragraph — the canonical "no content" value. */
+export const EMPTY_TIPTAP_DOC: JSONContent = {
+ type: 'doc',
+ content: [{ type: 'paragraph' }],
+}
+
+/** True when a TipTap doc contains nothing but empty paragraph(s), so it should be treated as blank. */
+export function isEffectivelyEmptyTiptapDoc(doc: JSONContent): boolean {
+ if (doc.type !== 'doc') {
+ return false
+ }
+
+ if (!doc.content || doc.content.length === 0) {
+ return true
+ }
+
+ if (doc.content.length !== 1 || doc.content[0].type !== 'paragraph') {
+ return false
+ }
+
+ const paragraphContent = doc.content[0].content
+ if (!paragraphContent || paragraphContent.length === 0) {
+ return true
+ }
+
+ return paragraphContent.every((node) => node.type === 'text' && !node.text)
+}
+
+/**
+ * Parse markdown into a TipTap doc using the given manager, expanding flattened tables first.
+ * Falls back to a single plain-text paragraph if the markdown is malformed or doesn't parse to a doc.
+ */
+export function markdownToTiptapDoc(manager: MarkdownManager, markdown: string | null | undefined): JSONContent {
+ if (!markdown || markdown.trim() === '') {
+ return EMPTY_TIPTAP_DOC
+ }
+
+ try {
+ const parsed = manager.parse(expandFlattenedMarkdownTables(markdown)) as JSONContent
+ if (parsed.type === 'doc') {
+ return parsed
+ }
+ } catch {
+ // Fall through to plain paragraph fallback for malformed markdown.
+ }
+
+ return {
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: markdown }],
+ },
+ ],
+ }
+}
+
+/** Serialize a TipTap doc to markdown using the given manager. Empty docs and failures yield ''. */
+export function tiptapDocToMarkdown(manager: MarkdownManager, doc: JSONContent): string {
+ try {
+ if (isEffectivelyEmptyTiptapDoc(doc)) {
+ return ''
+ }
+
+ return manager.serialize(doc).trimEnd()
+ } catch {
+ return ''
+ }
+}
+
+/** True when markdown survives a parse -> serialize -> parse round trip unchanged (i.e. the editor won't mangle it). */
+export function isTiptapMarkdownRoundTripSafe(manager: MarkdownManager, markdown: string | null | undefined): boolean {
+ if (!markdown || markdown.trim() === '') {
+ return true
+ }
+
+ try {
+ const expanded = expandFlattenedMarkdownTables(markdown)
+ const originalDoc = manager.parse(expanded) as JSONContent
+ const roundTripDoc = manager.parse(manager.serialize(originalDoc).trimEnd()) as JSONContent
+ return JSON.stringify(originalDoc) === JSON.stringify(roundTripDoc)
+ } catch {
+ return false
+ }
+}
+
+export type TiptapMarkdownConverter = {
+ markdownToDoc: (markdown: string | null | undefined) => JSONContent
+ docToMarkdown: (doc: JSONContent) => string
+ isRoundTripSafe: (markdown: string | null | undefined) => boolean
+}
+
+/**
+ * Build a markdown <-> TipTap doc converter bound to a set of extensions. Each editor (text card,
+ * AI prompt, etc.) supplies its own extensions but shares the parse/serialize/empty/round-trip logic.
+ */
+export function createTiptapMarkdownConverter(extensions: Extensions): TiptapMarkdownConverter {
+ const manager = new MarkdownManager({ extensions })
+ return {
+ markdownToDoc: (markdown) => markdownToTiptapDoc(manager, markdown),
+ docToMarkdown: (doc) => tiptapDocToMarkdown(manager, doc),
+ isRoundTripSafe: (markdown) => isTiptapMarkdownRoundTripSafe(manager, markdown),
+ }
+}